iOS

1、NSURLSession基础

 NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS,所以也可以使用。NSURLConnection上传图片,可以自己找资料。

 NSURLConnection相对于NSURLSession,安全性低。NSURLConnection下载有峰值,比较麻烦处理。

 尽管适配最低版本iOS7,也可以使用NSURLSession。AFN已经不支持NSURLConnection。

 NSURLSession:会话。默认是挂起状态,如果要请求网络,需要开启。

 [NSURLSession sharedSession] 获取全局的NSURLSession对象。在iPhone的所有app共用一个全局session.

 NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask

 NSURLSessionDownloadTask -> NSURLSessionTask

 NSURLSessionDownloadTask下载,默认下载到tmp文件夹。下载完成后删除临时文件。所以我们要在删除文件之前,将它移动到Cache里。

1)根据URL创建网络任务(get)

//创建URL

NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];

//创建请求

//    NSURLRequest * request = [NSURLRequest requestWithURL:url];

//创建Session

NSURLSession * session = [NSURLSession sharedSession];

//创建任务

NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

}];

//开启网络任务

[task resume];

2)根据request创建网络任务(get)

//创建URL

NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];

//创建请求

NSURLRequest * request = [NSURLRequest requestWithURL:url];

//创建Session

NSURLSession * session = [NSURLSession sharedSession];

//创建任务

NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); 

}];

//开启网络任务

[task resume];    

3)根据request创建网络任务(post)

NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php"];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

//设置请求方法

request.HTTPMethod = @"POST";

//设置请求体

request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding];

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

}] resume];   

4)网络下载任务

NSURL * url = [NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSURLSession * session = [NSURLSession sharedSession];

NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    //location 下载到沙盒的地址

    NSLog(@"下载完成%@",location);

    //response.suggestedFilename 响应信息中的资源文件名

    NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

    NSLog(@"缓存地址%@",cachesPath);

    //获取文件管理器

    NSFileManager * mgr = [NSFileManager defaultManager];

    //将临时文件移动到缓存目录下

    //[NSURL fileURLWithPath:cachesPath] 将本地路径转化为URL类型

    //URL如果地址不正确,生成的url对象为空

    [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];

}];

[downloadTask resume];

2、NSURLSession 代理方法

1)设置代理的方式

NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

2)代理方法

1、接收到服务器响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask

didReceiveResponse:(NSURLResponse *)response

 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler 
 
//允许接受服务器回传数据

completionHandler(NSURLSessionResponseAllow);
2、接收服务器回传的数据,有可能执行多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask

    didReceiveData:(NSData *)data 
3、请求成功或失败

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

3、NSURLSessionDownload 代理方法

1) 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次

 bytesWritten 单次写入多少
 totalBytesWritten  已经写入了多少

 totalBytesExpectedToWrite 文件总大小

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite 

//打印下载百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
2)下载完成

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

didFinishDownloadingToURL:(NSURL *)location

4、实现大文件下载挂起状态


//暂停就是将任务挂起 (暂停)暂停在某位置,并将此位置编程全局变量,以便于进行断点续传
    
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        
   //保存已下载的数据
   self.resumeData = resumeData;
}];

//可以使用ResumeData创建任务 (继续),从某位置继续下载
    
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    
//开启继续下载
[self.task resume];
原文地址:https://www.cnblogs.com/PSSSCode/p/5304343.html