IOS 网络开发NSURLSession(四)UploadTask(上传数据+图片)
2015-04-02 16:15
453 查看
原创blog,转载请注明出处
blog.csdn.net/hello_hwc
前言:
UploadTask继承自DataTask。不难理解,因为UploadTask只不过在Http请求的时候,把数据放到Http Body中。所以,用UploadTask来做的事情,通常直接用DataTask也可以实现。不过,能使用封装好的API会省去很多事情,何乐而不为呢?
Demo下载链接
http://download.csdn.net/detail/hello_hwc/8557791
Demo里包括了三种Task的使用,我想对想要学习NSURLSession的初学者还是有点帮助的。
使用一个工具网站,想要学习RestAPI的同学可以使用这个网站的API做一些练习。
http://jsonplaceholder.typicode.com/
上传图片,图片可以拍照,也可以从相册里选取,上传的返回data是一个html网页,用webview显示。
这里的上传服务器也是选择一个共工具网站
http://www.freeimagehosting.net/upl.php
HTTP header的具体信息参见Wiki,常用的header一定要熟悉
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
使用以下两个函数初始化
Session会自动计算Content-length的Header
通常,还需要提供一些服务器需要的Header,Content-Type就往往需要提供。
File-如果对象在磁盘上,这样做有助于降低内存使用。
使用以下两个函数进行初始化
同样,会自动计算Content-Length,如果App没有提供Content-Type,Session会自动创建一个。如果Server需要额外的Header信息,也要提供。
Stream
使用这个函数创建
注意,这种情况下一定要提供Server需要的Header信息,例如Content-Type和Content-Length。
使用Stream一定要实现这个代理方法,因为Session没办法在重新尝试发送Stream的时候找到数据源。(例如需要授权信息的情况)。这个代理函数,提供了Stream的数据源。
NSURLSessionDataDelegate,NSURLSessionDelegate,NSURLSessionTaskDelegate同样适用于UploadTask
代理函数
后续:网络部分,还会更新授权,证书一篇,AFNetworking一篇,一些网络的基本概念一篇。然后,转向更新数据存储这一块(CoreData以及IOS的文件系统)。
欢迎关注我的IOS-SDK详解专栏
http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html
blog.csdn.net/hello_hwc
前言:
UploadTask继承自DataTask。不难理解,因为UploadTask只不过在Http请求的时候,把数据放到Http Body中。所以,用UploadTask来做的事情,通常直接用DataTask也可以实现。不过,能使用封装好的API会省去很多事情,何乐而不为呢?
Demo下载链接
http://download.csdn.net/detail/hello_hwc/8557791
Demo里包括了三种Task的使用,我想对想要学习NSURLSession的初学者还是有点帮助的。
Demo效果
上传数据使用一个工具网站,想要学习RestAPI的同学可以使用这个网站的API做一些练习。
http://jsonplaceholder.typicode.com/
上传图片,图片可以拍照,也可以从相册里选取,上传的返回data是一个html网页,用webview显示。
这里的上传服务器也是选择一个共工具网站
http://www.freeimagehosting.net/upl.php
一 NSURLSessionUploadTask概述
1.1NSMutableURLRequest
上传数据的时候,一般要使用REST API里的PUT或者POST方法。所以,要通过这个类来设置一些HTTP配置信息。常见的包括timeoutInterval //timeout的时间间隔 HTTPMethod //HTTP方法 //设置HTTP表头信息 – addValue:forHTTPHeaderField: – setValue:forHTTPHeaderField:
HTTP header的具体信息参见Wiki,常用的header一定要熟悉
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
1.2 三种上传数据的方式
NSData - 如果对象已经在内存里使用以下两个函数初始化
uploadTaskWithRequest:fromData: uploadTaskWithRequest:fromData:completionHandler:
Session会自动计算Content-length的Header
通常,还需要提供一些服务器需要的Header,Content-Type就往往需要提供。
File-如果对象在磁盘上,这样做有助于降低内存使用。
使用以下两个函数进行初始化
uploadTaskWithRequest:fromFile: uploadTaskWithRequest:fromFile:completionHandler:
同样,会自动计算Content-Length,如果App没有提供Content-Type,Session会自动创建一个。如果Server需要额外的Header信息,也要提供。
Stream
使用这个函数创建
uploadTaskWithStreamedRequest:
注意,这种情况下一定要提供Server需要的Header信息,例如Content-Type和Content-Length。
使用Stream一定要实现这个代理方法,因为Session没办法在重新尝试发送Stream的时候找到数据源。(例如需要授权信息的情况)。这个代理函数,提供了Stream的数据源。
URLSession:task:needNewBodyStream:
1 .3 代理方法
使用这个代理方法获得upload的进度。其他的代理方法NSURLSessionDataDelegate,NSURLSessionDelegate,NSURLSessionTaskDelegate同样适用于UploadTask
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
二 上传数据
核心代码如下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];
三 上传图片
核心部分代码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; }
后续:网络部分,还会更新授权,证书一篇,AFNetworking一篇,一些网络的基本概念一篇。然后,转向更新数据存储这一块(CoreData以及IOS的文件系统)。
欢迎关注我的IOS-SDK详解专栏
http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html
相关文章推荐
- iOS开发之网络编程--5、NSURLSessionUploadTask+NSURLSessionDataDelegate代理上传
- iOS开发 ----- 网络请求5 ----- NSURLsession实现上传数据
- ios开发进阶之网络04 数据解析 文件下载上传
- IOS开发—网络请求、上传下载、断点续传(NSURLSession)
- iOS开发-使用NSURLSession实现文件断点下载,文件离线续传以及图片上传
- AF ios开发之网络数据的下载与上传
- iOS开发 ----- 网络请求3 ----- 上传数据
- ios开发 利用AFNetworking实现同时上传字符串与图片数据
- iOS基础8:自定义MyData/自定义SQLite用于网络判断,版本判断,图片缓存处理,下载或者上传的GET或POST请求,加密手段,.数据解析
- ios开发之网络数据的下载与上传
- 【iOS开发】SDWebImage框架,加载图片,失败之后,居然直接跳过不再去请求网络数据了?
- iOS多线程与网络开发之使用POST上传JSON数据 & 多值参数
- IOS开发Swift使用NSURLSessionUploadTask实现后台上传功能
- ios开发之网络数据的下载与上传
- IOS开发教程 - 如何通过二进制数据上传图片
- ios开发网络学习十二:NSURLSession实现文件上传
- iOS网络-NSURLSessionUploadTask文件上传
- iOS开发——网络篇——NSURLSession,下载、上传代理方法,利用NSURLSession断点下载,AFN基本使用,网络检测,NSURLConnection补充
- 【iOS开发-99】POST四种数据提交方式以及NSURLSession上传任务的一些知识
- ios开发之网络数据的下载与上传 要实现网络数据的下载与上传,主要有三种方式