iOS网络学习之“远离NSURLConnection 走进NSURLSession”
目前,在iOS的开发中,NURLConnection已经成为了过去式,现在的NSURLConnection已经deprected(iOS7之后),取而代之的是NSURLSession。而且AFNetworking 也已经换成了NSURLSession。既然是大势所趋,现总结NSURLSession用法如下:
首先,是根据简单地按钮实现对应的网络操作:

1.NSURLSessiion 的GET网络请求:
要实现网络请求,首先,要准备好URLl 和 必要的参数,而GET最大的特点就是参数是直接的拼接在URL的后面,(路径?参数名=参数值)。然后,就可以通过NSURLSession和NSURLSessionTask愉快的进行GET网络请求了。注意,task要手动开启[task resume];。
具体使用代码如下:
- (IBAction)oneAction:(UIButton *)sender {
/**
* get请求
*
*/
NSString * name=@"jredu";
NSString * psw=@"123";
NSURL * url=[NSURLURLWithString:[NSStringstringWithFormat:@"http://localhost/logo.php?userName=%@&pwd=%@",name,psw]];
//>初始化session
NSURLSession * session=[NSURLSessionsharedSession];
NSURLSessionTask * task=[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//将返回的二进制数据转为字符串
NSString * str=[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}];
//开始任务
[task resume];
}
2.使用NSURLSession进行POST网络请求:
通过POST方式请求网络,同样是准备好URL,而与GET方式的不同之处:POST时,所需的参数并不是拼接在URL上的,POST的参数通过NSURLRequest传递(NSData);
准备好参数和URL之后任然是通过NSURLSession和NSURLSessionTask进行网络请求。同样注意:手动开启任务[task resume];
具体的使用代码如下:
#pragma mark - post请求
- (IBAction)twoAction:(UIButton *)sender { NSString *name=@"codeJerenal";
NSString *psw=@""; NSURL * url =[NSURLURLWithString:@"http://localhost/login_post.php"]; NSString * dataStr=[NSStringstringWithFormat:@"userName=%@&psw=%@",name,psw];
/** 字符串转data */
NSData * data=[dataStr dataUsingEncoding:NSUTF8StringEncoding]; /** 初始化可变的请求--设置数据 */
NSMutableURLRequest * request=[NSMutableURLRequestrequestWithURL:url]; [request setHTTPMethod:@"POST"];
[request setHTTPBody:data]; /** 初始化session */
NSURLSession * session=[NSURLSessionsharedSession]; NSURLSessionTask * task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { /** data转字符串调用类方法 */
NSString *retutnStr=[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",retutnStr);
}]; //>开始任务
[task resume];
}
3,使用NSURLSession下载:
要下载数据,首先,要给出要下载的资源的网络路径URL;
NSURLSession 可以通过NSURLRequest初始化NSURLSession下载,也可以直接使用URL;
下载成功之后的文件、数据会放在沙盒中的tmp文件中,作为一个临时的文件(返回的location就是其本地的URL),所以在下载成功之后的块中,要及时的将所下载的内容转移到Document中存放(通过NSFileManager)。在移动文件的过程中要注意location是本地的URL 所以,目的地路劲也是URL 应该使用[NSURL fileURLWithString:string];
在下载完成之后,还会返回一个,NSURLResponse * response,可以通过其中的属性response.suggestedFileame作为文件在本地的命名;
具体的使用如下所示:
#pragma mark - 下载数据
- (IBAction)sessionDownLoadAction:(UIButton *)sender { //>URL路径
NSURL * url=[NSURLURLWithString:@"http://localhost/test.zip"]; //>初始化session
NSURLSession * session=[NSURLSessionsharedSession]; //>定义request
NSURLRequest * request=[NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:]; //>定义任务
NSURLSessionDownloadTask * downLoadTask=[session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { //本地沙盒路径
NSString * path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; //文件下载后的存放路径-(转为本地URL使用)(字符串拼接方式,构造本地路径)
// NSString * fPath=[path stringByAppendingPathComponent:response.suggestedFilename];
/** 转换 */
// NSURL * desUrl=[NSURL fileURLWithPath:fPath]; /** 为本地路径准备path (格式化方式,构造本地路径)*/
NSString * filePath=[NSStringstringWithFormat:@"file://%@/%@",path,response.suggestedFilename]; /** 转为本地的URL */
NSURL * destinationUrl=[NSURLURLWithString:filePath]; //移动
NSFileManager * manager =[NSFileManagerdefaultManager]; NSError * error2;
BOOL isSuccess = [manager moveItemAtURL:location toURL:destinationUrl error:&error2];
if (isSuccess) { NSLog(@"成功"); }else{ NSLog(@"失败");
NSLog(@"%@",error2);
} }];
[task resume];
}
4,NSURLSession实现下载的暂停和继续;
①:过程中要用到代理方法,而NSURLSession是在初始化的同时设置代理的,并且同时进行下载的设置
NSURLSessionConfiguration
参数一 session配置
参数二设置代理
参数三设置代理队列
NSURLSession * session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
②:通过按钮(或其他的方式)控制下载的暂停继续:
核心:取消下载任务并保存已经下载的数据
[self.downTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
self.resumeData=resumeData;
}];
核心: 通过之前保存的已经下载的数据,继续下载
self.downTask =[self.session downloadTaskWithResumeData:self.resumeData];
[self.downTask resume];
#pragma mark - 控制起停按钮,点击事件
- (void) clickAction:(UIButton *)button{ button.selected=!button.selected;
if (button.selected) { [self.downTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
/** 全局,用作断点下载存放已经下载的数据*/
self.resumeData=resumeData;
}]; }else{ self.downTask =[self.session downloadTaskWithResumeData:self.resumeData]; /** 重新启动任务 */
[self.downTask resume];
} }
③:下载过程中的主要代理方法
#pragma mark - 下载数据的代理方法 /**
* 代理方法:每次数据下载成功调用方法
*
* @param session 代理的session
* @param downloadTask 代理的task
* @param bytesWritten 本次下载的内容长度
* @param totalBytesWritten 已经下载的总的内容的长度
* @param totalBytesExpectedToWrite 需要下载的文件的总长度
*/
- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ NSLog(@"%lld===%lld=====%lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite); /** 主线程显示下载进度 */
dispatch_async(dispatch_get_main_queue(), ^{
if (totalBytesWritten==totalBytesExpectedToWrite) { _curProgress.frame=CGRectMake(, , , );
}else{ _curProgress.frame=CGRectMake(, , totalBytesWritten*(1.0)/totalBytesExpectedToWrite*(1.0)*, );
/** 随机背景色 */
_curProgress.backgroundColor=[UIColorcolorWithRed:arc4random_uniform()/.0green:arc4random_uniform()/.0blue:arc4random_uniform()/.0alpha:];
} }); }
/**
* 代理方法:下载完成时调用--已经下载的文件从临时存放处移动到document中
*
* @param session 代理的session
* @param downloadTask 代理的task
* @param location 下载文件的临时存放路径
*/
- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ NSString * documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString * filePath =[documentPath stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSURL * loaclUrl =[NSURLfileURLWithPath:filePath];
NSLog(@"%@",loaclUrl); //移动
NSError * err;
BOOL isSuccess=[[NSFileManagerdefaultManager] moveItemAtURL:location toURL:loaclUrl error:&err];
if (isSuccess) {
NSLog(@"下载成功");
}else{ NSLog(@"失败");
NSLog(@"%@",err);
} }
#pragma mark *** 下载结束
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ /**
如果是其他的原因导致下载失败,程序会走本方法,可以通过
self.resumeData = error[NSURLSessionDownloadTaskResumeData];
找到已经下载的数据,解决失败原因之后,可以继续下载
*/ if (error) {
NSLog(@"%@",error);
}else { NSLog(@"成功");
} }
iOS网络学习之“远离NSURLConnection 走进NSURLSession”的更多相关文章
- ios网络学习------4 UIWebView的加载本地数据的三种方式
ios网络学习------4 UIWebView的加载本地数据的三种方式 分类: IOS2014-06-27 12:56 959人阅读 评论(0) 收藏 举报 UIWebView是IOS内置的浏览器, ...
- ios网络学习------6 json格式数据的请求处理
ios网络学习------6 json格式数据的请求处理 分类: IOS2014-06-30 20:33 471人阅读 评论(3) 收藏 举报 #import "MainViewContro ...
- ios网络学习------3 用非代理方法实现异步post请求
#pragma mark - 这是私有方法.尽量不要再方法中直接使用属性,由于一般来说属性都是和界面关联的,我们能够通过參数的方式来使用属性 #pragma mark post登录方法 -(void) ...
- ios开发网络学习三:NSURLConnection小文件大文件下载
一:小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDele ...
- ios开发网络学习四:NSURLConnection大文件断点下载
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...
- ios网络学习------8 xml格式数据的请求处理 用代码块封装
#pragma mark 载入xml - (void)loadXML { //获取网络数据. NSLog(@"load xml"); //从webserver载入数据 NSStri ...
- ios网络学习------1get post异步请求
网络请求的步骤: get请求: #pragma mark - 这是私有方法,尽量不要再方法中直接使用属性,由于一般来说属性都是和界面关联的,我们能够通过參数的方式来使用属性 #pragma mark ...
- Snail—iOS网络学习之得到网络上的数据
在开发项目project中,尤其是手机APP,一般都是先把界面给搭建出来.然后再从网上down数据 来填充 那么网上的数据是怎么得来的呢,网络上的数据无非就经常使用的两种JSON和XML 如今 大部分 ...
- ios网络学习------11 原生API文件上传之断点续传思路
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaHVhbmcyMDA5MzAzNTEz/font/5a6L5L2T/fontsize/400/fill/I0 ...
随机推荐
- DIY(码表)制作实验
代码: #include<reg52.h>typedef unsigned char u8;typedef unsigned int u16;/********端口定义********* ...
- Git删除tag
git tag -d v2016062101 删除本地tag git push origin --delete tag v2016062101 删除远程tag
- sqlserver插入时发生在“xxx”处关键发生错误
今天知道了一个小技巧,当你的数据库表名为user时会sqlserver的表发生冲突,所以因该将user这样用[user],ok 一切搞定 .
- ubuntu下JDK的安装
硬盘上有下载好的JDK,直接解压后配置profile环境变量就行 export JAVA_HOME=/usr/lib/jvm/java-8-oracle export JRE_HOME=${JAVA_ ...
- CentOS下crond定时任务详细介绍
目录 1.定时任务crond介绍... 2.crond定时任务限权... 3.Crontab用法... 4.Crontab命令的书写格式... 5.定时服务器时间同步... 6.写定时任务注意点.. ...
- 比较详细Python正则表达式操作指南(re使用)
比较详细Python正则表达式操作指南(re使用) Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式.Python 1.5之前版本则是通过 regex 模块提供 E ...
- thinkphp连接数据库
版本:3.1.1 连接数据库的具体位置 thinkphp/Config/convention.php,默认修改数据库在这里就可以了 但是为了方便,把数据库配置写到Index/Conf/config.p ...
- $().index() 两种用法
第一种:获得第一个 p 元素的名称和值: $(this).index() <script type="text/javascript"> $(document).rea ...
- AspNet Identity and IoC Container Registration
https://github.com/trailmax/IoCIdentitySample TL;DR: Registration code for Autofac, for SimpleInject ...
- 将excel文件中的数据导入到mysql
·在你的表格中增加一列,利用excel的公式自动生成sql语句,具体方法如下: 1)增加一列(假设是D列) 2)在第一行的D列,就是D1中输入公式:=CONCATE ...