一 NSURLSessionUploadTask概述
1.1NSMutableURLRequest
上傳數(shù)據(jù)的時候里逆,一般要使用REST API里的PUT或者POST方法驶忌。所以,要通過這個類來設(shè)置一些HTTP配置信息毡代。常見的包括
timeoutInterval //timeout的時間間隔
HTTPMethod //HTTP方法
//設(shè)置HTTP表頭信息
– addValue:forHTTPHeaderField:
– setValue:forHTTPHeaderField:
HTTP header的具體信息參見Wiki,常用的header一定要熟悉
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
1.2 三種上傳數(shù)據(jù)的方式
NSData - 如果對象已經(jīng)在內(nèi)存里
使用以下兩個函數(shù)初始化
uploadTaskWithRequest:fromData:
uploadTaskWithRequest:fromData:completionHandler:
Session會自動計算Content-length的Header
通常,還需要提供一些服務(wù)器需要的Header戚宦,Content-Type就往往需要提供。
File-如果對象在磁盤上锈嫩,這樣做有助于降低內(nèi)存使用受楼。
使用以下兩個函數(shù)進行初始化
uploadTaskWithRequest:fromFile:
uploadTaskWithRequest:fromFile:completionHandler:
同樣,會自動計算Content-Length,如果App沒有提供Content-Type,Session會自動創(chuàng)建一個呼寸。如果Server需要額外的Header信息艳汽,也要提供。
Stream
使用這個函數(shù)創(chuàng)建
uploadTaskWithStreamedRequest:
注意对雪,這種情況下一定要提供Server需要的Header信息河狐,例如Content-Type和Content-Length。
使用Stream一定要實現(xiàn)這個代理方法瑟捣,因為Session沒辦法在重新嘗試發(fā)送Stream的時候找到數(shù)據(jù)源馋艺。(例如需要授權(quán)信息的情況)。這個代理函數(shù)迈套,提供了Stream的數(shù)據(jù)源捐祠。
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桑李;
二 上傳數(shù)據(jù)
核心代碼如下
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@http://jsonplaceholder.typicode.com/posts]];
[request addValue:@application/json forHTTPHeaderField:@Content-Type];//這一行一定不能少踱蛀,因為后面是轉(zhuǎn)換成JSON發(fā)送的
[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];
代理函數(shù)
-(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;
}