IOS Web Development Nsurlsession (iv) uploadtask (upload data + image)

Source: Internet
Author: User

Original blog, reproduced please indicate the source
Blog.csdn.net/hello_hwc

Objective:
Uploadtask inherits from Datatask. It's not hard to understand, because Uploadtask simply puts the data into the HTTP body when the HTTP request is made. So, the thing that uses uploadtask to do, usually directly with Datatask also can realize. However, the ability to use the encapsulated API will save a lot of things, why not?
Demo Download link
http://download.csdn.net/detail/hello_hwc/8557791
The demo includes the use of three tasks, which I think is a bit helpful to beginners who want to learn nsurlsession.

Demo effect

Uploading data
Using a tool website, students who want to learn RESTAPI can use the API of this website to do some exercises.
http://jsonplaceholder.typicode.com/

Upload pictures, pictures can take pictures, can also be selected from the album, upload the return data is an HTML page, with WebView display.
The upload server here is also select a common tools site
http://www.freeimagehosting.net/upl.php

A nsurlsessionuploadtask overview 1.1NSMutableURLRequest

When uploading data, it is common to use the put or post method in the rest API. So, to set up some HTTP configuration information through this class. Common include

timeoutInterval //timeout的时间间隔HTTPMethod //HTTP方法//设置HTTP表头信息– addValue:forsetValue:forHTTPHeaderField:

HTTP Header specific information refer to the wiki, the common header must be familiar with
Http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

1.2 Three ways to upload data

NSData-If the object is already in memory
Class with the following two functions

uploadTaskWithRequest:fromDatauploadTaskWithRequest:fromData:completionHandler

Session will automatically calculate the Content-length header
Often, it is also necessary to provide some of the header,content-type that a server needs.

file-if the object is on disk, doing so can help reduce memory usage.
Class with the following two functions

uploadTaskWithRequest:fromFileuploadTaskWithRequest:fromFile:completionHandler:

Similarly, content-length is automatically calculated, and if the app does not provide content-type,session it will automatically create one. If the server requires additional header information, it is also provided.

Stream
Use this function to create

uploadTaskWithStreamedRequest:

Note that in this case, be sure to provide the header information that the server needs, such as Content-type and Content-length.

Use the stream to implement this proxy method, because the session has no way to find the data source when trying to send the stream again. (such as where authorization information is required). This proxy function provides the data source for the stream.

URLSession:task:needNewBodyStream:
1.3 Proxy method

Use this proxy method to get the upload progress. Other proxy methods
The nsurlsessiondatadelegate,nsurlsessiondelegate,nsurlsessiontaskdelegate is also suitable for uploadtask

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
Two upload data

The core code is as follows

    nsmutableurlrequest* Request = [nsmutableurlrequestrequestwithurl:[Nsurl urlwithstring:@"Http://jsonplaceholder.typicode.com/posts"]]; [Request addvalue:@"Application/json"forhttpheaderfield:@"Content-type"];//This line must not be less, because the back is converted intoJSONSend the [Request addvalue:@"Application/json"forhttpheaderfield:@"Accept"]; [Request sethttpmethod:@"POST"]; [Request Setcachepolicy:Nsurlrequestreloadignoringcachedata]; [Request Settimeoutinterval: -];nsdictionary* datatouploaddic = @{self.keytextfield.text:self.valuetextfield.text};NSData* Data = [nsjsonserialization datawithjsonobject:datatouploaddicOptionsnsjsonwritingprettyprintedError:nil];Nsurlsessionuploadtask* Uploadtask = [self.session uploadtaskwithrequest:request fromdata:Datacompletionhandler:^(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];
Three uploaded images

Core Part Code

Nsmutableurlrequest * request = [Nsmutableurlrequest requestwithurl:[Nsurlurlwithstring:@"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: -]; NSData * ImageData = uiimagejpegrepresentation ( Self. ImageView. Image,1.0); Nsurlsessionuploadtask * Uploadtask = [ Self. SessionUploadtaskwithrequest:request fromdata:imagedata completionhandler:^ (NSData *data, NSURLResponse *response,Nserror*error) {NSString* Htmlstring = [[NSStringAlloc] Initwithdata:data encoding:nsutf8stringencoding]; Uploadimagereturnviewcontroller * RESULTVC = [ Self. Storyboardinstantiateviewcontrollerwithidentifier:@"RESULTVC"]; Resultvc. htmlstring= htmlstring; [ Self. NavigationcontrollerPUSHVIEWCONTROLLER:RESULTVC Animated:YES]; Self. Progressview. Hidden=YES; [ Self. SpinnerStopanimating]; [ Self. SpinnerRemovefromsuperview];    }]; [Uploadtask resume];

Agent 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;}

Follow up: Network part, also will update authorization, certificate one, afnetworking an article, some basic concept of network. Then, turn to update the data store this piece (CoreData and iOS file system).

Welcome to my ios-sdk detailed column
Http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html

IOS Web Development Nsurlsession (iv) uploadtask (upload data + image)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.