NSURLSession 使用

  NSURLSession 是随着ios 7一起发布的新类,目的是为了替代NSURLConnection。 NSURLSession能够完成所有NSURLConnection的功能,并且进行了非常大的功能扩充。ios 9 之后ios 就把NSURLConnection弃用。所以使用NSURLSession完成网络请求的处理,是大趋势。常见的第三方框架(AFNetworking,SDWebImage)也都跟新,使用NSURLSession。

  NSURLSession另一个重要的部分是会话任务,它负责加载数据,在客户端和服务器端进行文件的上传下载。

  

  通过前面的介绍大家可以看到,NSURLConnection完成的三个主要任务:获取数据(通常是JSON、XML等)、文件上传、文件下载。其实在NSURLSession时代,他们分别由三个任务来完成:NSURLSessionData、NSURLSessionUploadTask、NSURLSessionDownloadTask,这三个类都是NSURLSessionTask这个抽象类的子类,相比直接使用NSURLConnection,NSURLSessionTask支持任务的暂停、取消和恢复,并且默认任务运行在其他非主线程中,具体关系图如下:

使用介绍

//普通网络请求
- (void) request
{
    NSString *urlstr = @"http://developertest.deviceone.cn";
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:urlstr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *reData = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSLog(@"%@",reData);
    }] resume];
}
//下载
- (void)download
{
    NSString *urlStr = @"http://ds2.deviceone.net/Files/install/20151103/342c733d-c491-4e34-a25c-c7fd8c47c126.apk";
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];
    NSURLSession *session = [NSURLSession sharedSession];
    [[session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"downloadTaskWithRequest = %@",location);
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //下载好保存在本地一个临时的文件,需要保存
        NSString *fileName = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:response.suggestedFilename];
        NSLog(@"local file name : %@",fileName);
        [fileManager moveItemAtURL:location toURL:[NSURL URLWithString:fileName] error:nil];
        
    }] resume];
}

- (void)upload
{
    NSString *urlStr = @"http://developertest.deviceone.cn/test/upload";
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    request.HTTPMethod = @"POST";
    NSString *typeStr = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", @"boundary"];
    [request setValue:typeStr forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session =  [NSURLSession sharedSession];
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"0.jpg" ofType:nil];
    NSData *data = [self getHttpBodyWithFilePath:filePath formName:@"file" reName:@"test.jpg"];
    request.HTTPBody = data;
    [[session uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSLog(@"upload success:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        } else {
            NSLog(@"upload error:%@",error);
        }
    }] resume];
}

demo很简单,主要代码就是上面所说,TP

推荐博客

http://www.cnblogs.com/kenshincui/p/4042190.html#NSURLSession

http://annmeng.blog.51cto.com/3321237/1746703

原文地址:https://www.cnblogs.com/yzvictory/p/5302356.html