NSURLSession
2015-11-19 14:33
162 查看
快一年左右未在CSDN上发表新文章了,基本上都保存在自己的本地。难得闲下来,还是将自己的一些资料发布到网上供大家一起交流,参考。
NSURLSession是苹果一种HTTP网络请求方式,想必有经验的都知道在iOS开发中,HTTP网络请求方式有很多种。比如:
ASIHTTPRequest
AFNetworking等
在以前的开发中,我比较习惯使用ASIHTTPRequest,但是自从ARC之后,ASIHTTPRequest没有更新升级了,不过还是能够满足日常的开发需求,同时使用cocospods管理,ASIHTTPRequest在ARC的条件下,也比较方便了。当然ASIHTTPRequest与AFNetworking之间各有优缺点。同时毕竟是第三方库存在太大不确定的因素,为此,我在日常的开发当中,慢慢的移除第三方库或自己基于苹果提供的API进行二次封装,提供接口。好了,不废话了,切入本文的主题,NSURLSession的使用,直接上代码:
1、简单请求
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
NSURLSession *urlSession = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(@"data > %@", data);
}];
[dataTask resume];
// [dataTask suspend];
// [dataTask cancel];
NSURLSessionDownloadTask *downloadTask = [urlSession downloadTaskWithRequest:request
completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error)
{
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
NSURL *newFileLocation = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL] lastPathComponent]];
[[NSFileManager defaultManager] copyItemAtURL:location toURL:newFileLocation error:nil];
}];
[downloadTask resume];
NSURLSessionUploadTask *uploadTask = [urlSession uploadTaskWithRequest:request
fromData:nil
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
}];
[uploadTask resume];
2、POST请求
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"url地址"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[@"version=1.0.0&os_version=7.1.2&os_type=iOS" dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(@"获取到的数据>%@",
[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]);
}];
[dataTask resume];
相关文章推荐
- 进度条显示—正在加载中......
- Android 4.4前后版本读取图库图片和拍照完美解决方案
- JavaScript正则表达式实例
- UDP丢包及无序问题
- Java线程并发控制基础知识
- GO语言实现文件上传
- 设置表单的默认值、检测表单是否变更
- Remove Invalid Parentheses--Nice
- 用eclipse导入design需要注意的细节
- JS实现——Base64编码解码,带16进制显示
- java入门 第三季4
- 用rm递归删除子目录下所有.o后缀文件
- 磁盘同步rsync+sersync
- Xcode7 免证书真机调试
- MYSQL中limit的使用
- java入门 第三季3
- 。鸟哥私房菜
- AFNetWork 简单实用demo
- CentOS yum安装redis(转)
- java中的路径