IOS network development NSURLSession (4) UploadTask (upload data + image)
Original blog, reprinted, please indicate the source
Blog.csdn.net/hello_hwc
Preface:
UploadTask is inherited from DataTask. It is not hard to understand, because UploadTask only puts data in the Http Body during Http requests. Therefore, the use of UploadTask can also be implemented directly using DataTask. However, using encapsulated APIs saves a lot of trouble. Why not?
Demo download link
Http://download.csdn.net/detail/hello_hwc/8557791
The Demo contains three types of tasks. I think it is helpful for beginners who want to learn NSURLSession.
Demo Effect
Upload data
If you are using a tool website and want to learn RestAPI, you can use the API of this website to do some exercises.
Http://jsonplaceholder.typicode.com/
Upload an image. You can take a photo or select an image from the album. The returned data is an html webpage that is displayed in webview.
The upload server also chooses a common tool website.
Http://www.freeimagehosting.net/upl.php
An overview of NSURLSessionUploadTask 1.1 NSMutableURLRequest
When uploading data, you generally need to use the PUT or POST method in the rest api. Therefore, you need to use this class to set some HTTP configuration information. Common include
TimeoutInterval // timeout interval HTTPMethod // HTTP Method // set the HTTP header information-addValue: forHTTPHeaderField:-setValue: forHTTPHeaderField:
For more information about HTTP headers, see Wiki. You must be familiar with common headers.
Http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
1.2 three data upload Methods
NSData-if the object is already in memory
Use the following two functions for initialization:
uploadTaskWithRequest:fromData: uploadTaskWithRequest:fromData:completionHandler:
The Session automatically calculates the Content-length Header.
Generally, some headers are required for the server. Content-Type is usually required.
File-if the object is on the disk, this helps reduce memory usage.
Use the following two functions for initialization:
uploadTaskWithRequest:fromFile: uploadTaskWithRequest:fromFile:completionHandler:
Similarly, Content-Length is automatically calculated. If the App does not provide Content-Type, the Session will automatically create one. If the Server requires additional Header information, you must also provide it.
Stream
Use this function to create
uploadTaskWithStreamedRequest:
Note: In this case, you must provide the Header information required by the Server, such as Content-Type and Content-Length.
This proxy method must be implemented when Stream is used, because the Session cannot find the data source when sending Stream again. (For example, when authorization information is required ). This proxy function provides the Stream data source.
URLSession:task:needNewBodyStream:
1. 3 proxy method
Use this proxy method to get the upload progress. Other proxy Methods
NSURLSessionDataDelegate, NSURLSessionDelegate, and NSURLSessionTaskDelegate are also applicable to UploadTask
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
Ii. Upload data
The core code is as follows:
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: @ response [request addValue: @ application/json forHTTPHeaderField: @ Content-Type]; // This line must be rare, [request addValue: @ application/JSON forHTTPHeaderField: @ Accept]; [request setHTTPMethod: @ POST]; [request setCachePolicy: NSURLRequestReloadIgnoringCacheData]; [request se TTimeoutInterval: 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) {I F (! Error) {NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData: data options: kNilOptions error: nil]; self. responselabel. text = dictionary. description;} else {UIAlertController * alert = [UIAlertController alertControllerWithTitle: @ Error message: error. optional preferredStyle: Expected]; [alert addAction: [UIAlertAction actionWithTitle: @ OK style: UIAlertActionStyleCancel handler: nil]; [self presentViewController: alert animated: YES completion: nil] ;}}]; [uploadtask resume];
3. upload images
Core code
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];
Proxy Functions
-(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;}
Later: in the network section, authorization, certificate, AFNetworking, and basic concepts of some networks will be updated. Then, we switched to the data storage (CoreData and IOS File System ).