NSURLSession使用详解

1 NSURLSession和NSURLConnection

NSURLSessionNSURLConnection的替代者,在2013年苹果全球开发者大会(WWDC2013)随iOS7一起发布,是对NSURLConnection进行了重构优化后的新的网络访问接口。从iOS9.0开始, NSURLConnection中发送请求的两个方法已过期(同步请求,异步请求),初始化网络连接(initWithRequest: delegate:)的方法也被设置为过期,系统不再推荐使用,建议使用NSURLSession发送网络请求。因此后面只针对NSURLSession进行讲解。

2 NSURLSession使用

NSURLSession针对下载/上传等复杂的网络操作提供了专门的解决方案,针对普通、上传和下载分别对应三种不同的网络请求任务:NSURLSessionDataTask, NSURLSessionUploadTaskNSURLSessionDownloadTask。创建的task都是挂起状态,需要resume才能执行。

2.1 普通请求任务

- (void)sessionDataTask {
    // 1.请求路径
    NSURL *url = [NSURL URLWithString:@"http://rap2api.taobao.org/app/mock/163155/gaoshilist"];
    // 2.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 3.创建 session 对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    // 普通任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse * response, NSError *error) {
        if (error) {
            NSLog(@"NSURLSessionDataTaskerror:%@",error);
            return;
        }
        
        // 解析数据
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"NSURLSessionDataTaskdic:%@",dic);
        
        //5.解析数据
        NSLog(@"NSURLSessionDataTask:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
    // 执行 task
    [dataTask resume];
}

2.2 上传任务

//上传请求
- (void)uploadSessionDataTask {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/iostest.php"]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [self getDataBody];
    
    [request setValue:[NSString stringWithFormat:@"%d",[self getDataBody].length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:[self getDataBody] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    [task resume];
}

//获取请求体内容
-(NSData *)getDataBody {
    NSMutableData *data = [NSMutableData data];
    
    NSString *top = [NSString stringWithFormat:@"--%@\nContent-Disposition: form-data; name=\"file\"; filename=\"1.png\"\nContent-Type: image/png\n\n",boundary];
    
    NSString *bottom = [NSString stringWithFormat:@"\n--%@--\n\n",boundary];
    
    NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"]];
    
    [data appendData:[top dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:content];
    [data appendData:[bottom dataUsingEncoding:NSUTF8StringEncoding]];
    return data;
}

2.3 下载任务

注意两种task的创建方式,一种是使用completionHandler,一种是使用代理。注意如果使用了completionHandler,即使同时也实现了delegate,delegate仍不执行。

//download session
- (void)downloadSessionDataTask {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/e61190ef76c6a7efc0a0e1ebfffaaf51f2de667c.jpg"]];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    //1、第一种不使用completionHandler,则完成后的回调会调用到NSURLSessionDownloadDelegate的方法
    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request];
    
    //2、第二针使用completionHandler,完成后的回调则直接执行hanlder,即使实现了delegate方法也不去执行
//    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request
//                                                    completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        NSString *dirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//        NSString *path = [dirPath stringByAppendingPathComponent:@"1.jpg"];
//
//        NSFileManager *manager = [NSFileManager defaultManager];
//        if ([manager fileExistsAtPath:path isDirectory:NO]) {
//            [manager removeItemAtPath:path error:nil];
//        }
//
//        [manager moveItemAtPath:[location path] toPath:path error:nil];
//    }];
    [task resume];
}


#pragma mark -- NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    NSString *dirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *path = [dirPath stringByAppendingPathComponent:@"1.jpg"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path isDirectory:NO]) {
        [manager removeItemAtPath:path error:nil];
    }
    [manager moveItemAtPath:[location path] toPath:path error:nil];
}

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
    float percent = (float)fileOffset/expectedTotalBytes;
    NSLog(@"%f",percent);
}

//任务结束
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
    NSLog(@"%s",__func__);
}

你可能感兴趣的:(NSURLSession使用详解)