iOS网络开发之NSURLSession学习<4>
2015-10-20 19:08
651 查看
这篇文章会详细讲解
一.
1.
上传数据的时候,一般要使用REST API里的PUT或者POST方法。所以,要通过这个类来设置一些HTTP配置信息。常见的包括:
2.三种上传数据的方式
<1>NSData: 如果对象已经在内存里
uploadTaskWithRequest:fromData:
uploadTaskWithRequest:fromData:completionHandler:
Session会自动计算Content-length的Header
通常,还需要提供一些服务器需要的Header,Content-Type等。
<2>File:如果对象在磁盘上,这样做有助于降低内存使用
使用以下两个函数进行初始化
uploadTaskWithRequest:fromFile:
uploadTaskWithRequest:fromFile:completionHandler:
同样,会自动计算Content-Length,如果App没有提供Content-Type,Session会自动创建一个。如果Server需要额外的Header信息,也要提供。
<3>Stream
使用这个函数创建
注意,这种情况下一定要提供Server需要的Header信息,例如Content-Type和Content-Length。
使用Stream一定要实现这个代理方法,因为Session没办法在重新尝试发送Stream的时候找到数据源。(例如需要授权信息的情况)。这个代理函数,提供了Stream的数据源。
二.代理方法:
使用这个代理方法获得upload的进度
三.示例代码
1.上传数据
2.上传图片
代理方法:
NSURLSessionUploadTask内容
UploadTask继承自
DataTask。不难理解,因为
UploadTask只不过在
Http请求的时候,把数据放到
Http Body中。所以,用
UploadTask来做的事情,通常直接用
DataTask也可以实现。不过,能使用封装好的API会省去很多事情,何乐而不为呢?
一.
NSURLSessionUploadTask概述
1.
NSMutableURLRequest
上传数据的时候,一般要使用REST API里的PUT或者POST方法。所以,要通过这个类来设置一些HTTP配置信息。常见的包括:
timeoutInterval//timeout的时间间隔
HTTPMethod//HTTP方法
– addValue:forHTTPHeaderField:或者
– setValue:forHTTPHeaderField://设置HTTP表头信息
2.三种上传数据的方式
<1>NSData: 如果对象已经在内存里
uploadTaskWithRequest:fromData:
uploadTaskWithRequest:fromData:completionHandler:
Session会自动计算Content-length的Header
通常,还需要提供一些服务器需要的Header,Content-Type等。
<2>File:如果对象在磁盘上,这样做有助于降低内存使用
使用以下两个函数进行初始化
uploadTaskWithRequest:fromFile:
uploadTaskWithRequest:fromFile:completionHandler:
同样,会自动计算Content-Length,如果App没有提供Content-Type,Session会自动创建一个。如果Server需要额外的Header信息,也要提供。
<3>Stream
使用这个函数创建
uploadTaskWithStreamedRequest
注意,这种情况下一定要提供Server需要的Header信息,例如Content-Type和Content-Length。
使用Stream一定要实现这个代理方法,因为Session没办法在重新尝试发送Stream的时候找到数据源。(例如需要授权信息的情况)。这个代理函数,提供了Stream的数据源。
URLSession:task:needNewBodyStream:
二.代理方法:
使用这个代理方法获得upload的进度
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
三.示例代码
1.上传数据
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://jsonplaceholder.typicode.com/posts"]]; [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];//这一行一定不能少,因为后面是转换成JSON发送的 [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setHTTPMethod:@"POST"]; [request setCachePolicy:NSURLRequestReloadIgnoringCacheData]; [request setTimeoutInterval:20]; NSDictionary * dataToUploaddic = @{self.keytextfield.text:self.valuetextfield.text}; NSData * data = [NSJSONSerialization dataWithJSONObject:dataToUploaddic options:NSJSONWritingPrettyPrinted error:nil]; NSURLSessionUploadTask * uploadtask = [self.session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; self.responselabel.text = dictionary.description; }else{ UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Error" message:error.localizedFailureReason preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]]; [self presentViewController:alert animated:YES completion:nil]; } }]; [uploadtask resume];
2.上传图片
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.freeimagehosting.net/upload.php"]]; [request addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"]; [request addValue:@"text/html" forHTTPHeaderField:@"Accept"]; [request setHTTPMethod:@"POST"]; [request setCachePolicy:NSURLRequestReloadIgnoringCacheData]; [request setTimeoutInterval:20]; NSData * imagedata = UIImageJPEGRepresentation(self.imageview.image,1.0); NSURLSessionUploadTask * uploadtask = [self.session uploadTaskWithRequest:request fromData:imagedata completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString * htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; UploadImageReturnViewController * resultvc = [self.storyboard instantiateViewControllerWithIdentifier:@"resultvc"]; resultvc.htmlString = htmlString; [self.navigationController pushViewController:resultvc animated:YES]; self.progressview.hidden = YES; [self.spinner stopAnimating]; [self.spinner removeFromSuperview]; }]; [uploadtask resume];
代理方法:
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{ self.progressview.progress = totalBytesSent/(float)totalBytesExpectedToSend; }
相关文章推荐
- Linux网络编程---TCP三次握手,SYN洪水攻击,
- HTTP必知必会(转)
- iOS网络开发之NSURLSession学习<3>
- http://doc.okbase.net/fengshizty/archive/126397.html
- Fedora修改网络接口名称
- http server原理,nginx与php之间是如何工作的
- 虚拟机网络驱动(共享文件夹)不见了的解决方案-适用于win7~win10 and Windows Server 2008~Windows Server 2012R2
- 运营商网络中的"在线"加密(三)
- 基于openssl搭建https服务
- iOS网络开发之NSURLSession学习<2>
- TCP协议中的三次握手和四次挥手(图解)
- AFNetWorking 中使用HTTPS
- http://bbs.csdn.net/topics/390176122
- https跳转到http session丢失问题
- gre网络细节
- Linux网络编程---ICMP洪水攻击
- window.XMLHttpRequest对象详解
- Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)
- TCP/IP网络编程 基于Linux编程_3 --优于select的epoll
- TCP/IP网络编程 基于Linux编程_3 --优于select的epoll