欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NSURLSession的簡單使用

程序员文章站 2022-05-24 09:30:59
...

包括四個會話

  • 簡單會話-通過NSURLSession靜態方法+sharedSession獲得NSURLSession對象
NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxx/WebService.php?email=%@&type=%@&action=%@", @"[email protected]", @"JSON", @"query"];

    strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//將字符串轉化成URL字符串,例如"<"的URL編碼是"%3C"

    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
        ^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"请求完成...");
        if (!error) {
            NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadView:resDict];
            });
        } else {
            NSLog(@"error : %@", error.localizedDescription);
        }
    }];

    [task resume];

  • 默認會話(default session)-通過NSURLSession靜態方法+sessionWithConfiguration:或者+sessionWithConfiguration:delegate:delegateQueue:獲得NSURLSession對象
    1,以下為GET方法請求數據
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

2,以下是POST請求,GET請求是NSURLRequest,POST請求是NSMutableURLRequest

    NSString *strURL = @"http://xxx/WebService.php";

    NSURL *url = [NSURL URLWithString:strURL];

    NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"[email protected]", @"JSON", @"query"];
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];

    NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
        ^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"请求完成...");
        if (!error) {
            NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            [self reloadView:resDict];
        } else {
            NSLog(@"error : %@", error.localizedDescription);
        }
    }];

    [task resume];

3,下載圖片

- (IBAction)onClick:(id)sender {

    NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxx/download.php?email=%@&FileName=test1.jpg", @"[email protected]"];

    NSURL *url = [NSURL URLWithString:strURL];

    NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];

    [downloadTask resume];

}

#pragma mark -- 实现NSURLSessionDownloadDelegate委托协议
//下載中的方法,可以用來改變下載進度條
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    
    float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
    [self.progressView setProgress:progress animated:TRUE];
    NSLog(@"进度= %f", progress);
    NSLog(@"接收: %lld 字节 (已下载: %lld 字节)  期待: %lld 字节.", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}

//下載完成後調用的方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {

    NSLog(@"临时文件: %@\n", location);

    NSString *downloadsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) objectAtIndex:0];

    NSString *downloadStrPath = [downloadsDir stringByAppendingPathComponent:@"test1.jpg"];
    NSURL *downloadURLPath = [NSURL fileURLWithPath:downloadStrPath];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSError *error = nil;
    if ([fileManager fileExistsAtPath:downloadStrPath]) {
        [fileManager removeItemAtPath:downloadStrPath error:&error];
        if (error) {
            NSLog(@"删除文件失败: %@", error.localizedDescription);
        }
    }

    error = nil;

    if ([fileManager moveItemAtURL:location toURL:downloadURLPath error:&error]) {
        NSLog(@"文件保存: %@", downloadStrPath);
        UIImage *img = [UIImage imageWithContentsOfFile:downloadStrPath];
        self.imageView1.image = img;
        
    } else {
        NSLog(@"保存文件失败: %@", error.localizedDescription);
    }
}
  • 短暫會話(ephemeral session)-通過NSURLSessionConfiguration靜態方法+ephemeralSessionConfiguration獲得
  • 後臺會話(background session)-通過NSURLSessionConfiguration靜態方法+backgroundSessionConfigurationWithIdentifier:獲得

包括三種形式的任務

  • 數據任務(data task) NSURLSessionDataTask類
  • 上傳任務(upload task) NSURLSessionUploadTask類
  • 下載任務(download task) NSURLSessionDownloadTask類

转载于:https://www.jianshu.com/p/9927c7a87d57