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];
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· [WPF] 在RichTextBox中输出Microsoft.Extension.Logging库的
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一步一步教你部署ktransformers,大内存单显卡用上Deepseek-R1