NSURLSession基本使用
2015-08-25 09:10
561 查看
NSURLSession
使用步骤创建NSURLSession
创建Task
执行Task
NSURLSessionDataTask
GETNSURL *url = [NSURL URLWithString:@"http://124.25.226.186:32812/login?username=baoduit&pwd=baiduit"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 1.获得NSURLSession对象 NSURLSession *session = [NSURLSession sharedSession]; // 2.创建任务 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; // 3.启动任务 [task resume];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=baoduit&pwd=baoduit"]; // 1.获得NSURLSession对象 NSURLSession *session = [NSURLSession sharedSession]; // 2.创建任务 NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; // 3.启动任务 [task resume];
POST
NSURL *url = [NSURL URLWithString:@"http://123.25.226.186:32812/login"]; // 设置请求头 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; // 1.获得NSURLSession对象 NSURLSession *session = [NSURLSession sharedSession]; // 2.创建任务 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; // 3.启动任务 [task resume];
NSURLSessionDataDelegate代理注意事项
Task都是通过Session监听
// 1.获得NSURLSession对象 NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
+ NSURLSessionDataDelegate`默认不会接受数据`
/** * 1.接收到服务器的响应 */ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { NSLog(@"%s", __func__); NSLog(@"%@", [NSThread currentThread]); /* NSURLSessionResponseAllow: 去向处理服务器响应, 内部会调用[task cancle] NSURLSessionResponseCancel: 允许处理服务器的响应,才会继续接收服务器返回的数据 NSURLSessionResponseBecomeDownload: 讲解当前请求变为下载 */ completionHandler(NSURLSessionResponseAllow); } /** * 2.接收到服务器的数据(可能会被调用多次) */ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"%s", __func__); } /** * 3.请求成功或者失败(如果失败,error有值) */ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%s", __func__); }
NSURLSessionDownloadTask
DownloadTask默认已经实现边下载边写入// 1.创建request NSURL *url = [NSURL URLWithString:@"http://123.25.226.186:32812/resources/videos/minion_01.mp4"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2.创建session NSURLSession *session = [NSURLSession sharedSession]; // 3.创建下载任务 NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { NSLog(@"%@", location.absoluteString); NSFileManager *manager = [NSFileManager defaultManager]; NSString *toPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; toPath = [toPath stringByAppendingPathComponent:response.suggestedFilename]; // 将下载好的文件从location移动到cache [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:toPath] error:nil]; }]; // 4.开启下载任务 [task resume];
DownloadTask断点下载
暂停: suspend
继续: resume
取消: cancel
任务一旦被取消就无法恢复
区别并返回下载信息
//取消并获取当前下载信息 [self.task cancelByProducingResumeData:^(NSData *resumeData) { self.resumeData = resumeData; }]; // 根据用户上次的下载信息重新创建任务 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; [self.task resume];
DownloadTask监听下载进度
/** * 每当写入数据到临时文件时,就会调用一次这个方法 * totalBytesExpectedToWrite:总大小 * totalBytesWritten: 已经写入的大小 * bytesWritten: 这次写入多少 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { NSLog(@"正在下载: %.2f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite); } /* * 根据resumeData恢复任务时调用 * expectedTotalBytes:总大小 * fileOffset: 已经写入的大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { NSLog(@"didResumeAtOffset fileOffset = %lld , expectedTotalBytes = %lld", fileOffset, expectedTotalBytes); } /** * 下载完毕就会调用一次这个方法 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSLog(@"下载完毕"); // 文件将来存放的真实路径 NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; // 剪切location的临时文件到真实路径 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil]; } /** * 任务完成 */ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"didCompleteWithError"); }
离线断点下载
使用NSURLSessionDataTaskNSMutableURLRequest *reuqest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]]; // 核心方法, 实现从指定位置开始下载 NSInteger currentBytes = KCurrentBytes; NSString *range = [NSString stringWithFormat:@"bytes=%zd-", currentBytes]; [reuqest setValue:range forHTTPHeaderField:@"Range"]; // 核心方法, 自己实现边下载边写入 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data;
NSURLSessionUploadTask
设置设置请求头, 告诉服务器是文件上传multipart/form-data; boundary=lnj
必须自己
严格按照格式拼接请求体
请求体不能设置给request, 只能设置给fromData
The body stream and body data in this request object are ignored.
+
[[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }] resume];
注意:以下方法用于PUT请求
[self.session uploadTaskWithRequest:<#(nonnull NSURLRequest *)#> fromFile:<#(nonnull NSURL *)#>]
相关文章推荐
- Android 网络通信框架Volley简介
- 2016网络红人萧天
- HTTP中的重定向和请求转发的区别
- TCP和UDP的"保护消息边界"
- Linux 下apache httpd进程老死
- iOS网络-06-监听Iphone的网络状态
- TCP/IP协议知识科普
- 网络安全技术(二)
- Ubuntu Server配置wireless连接WPA2网络(interfaces)
- BZOJ 3931 网络吞吐量 (最短路+最大流)
- 想写一个网络游戏(PS:纯粹是为了好玩)
- TCP建立和解除连接过程
- tcpclient
- 在x86为arm 编译 httpd 2.2.31
- HTTP报文详解
- 帝云网络网站被攻击了怎么办?各类攻击应对方法
- 帝云网络五大技巧维护服务器安全
- 帝云网络服务器不稳定的影响因素有哪些
- 帝云网络选择服务器托管需考核哪五大关键点
- 使用httpclient实现http接口调用实例