1 , overview
N Nsurlsession is a new network interface in IOS7, which is tied to nsurlconnection.
n when the program is in the foreground, most of nsurlsession and nsurlconnection can replace each other
n Nsurlsession supports background network operations unless the user forcibly shuts down
N Nsurlsession provides the functionality:
P download data to memory via URL
P downloading data to the file system via a URL
P uploads data to the specified URL
P perform the above functions in the background
P for small data, such as user login, download small image, JSON & XML still use nsurlconnection asynchronous or synchronous method can
2 , nsurlsession the Use
n Use nsurlsessionconfiguration to configure Nsurlsession objects
n use Nsurlsession object to start a Nsurlsessiontask object
n can also use the system global Sharedsession Singleton to meet most of the requirements
N Note: Compared to nsurlconnection return processing, Nsurlsession provides a flexible way to return data, use a simple block method to process the return data, or use a more powerful delegate
3 , nsurlsessionconfiguration
n function: Used to define and configure Nsurlsession objects
N each Nsurlsession object can be set to different nsurlsessionconfiguration to meet the different types of network requests within the application
Three types of n nsurlsessionconfiguration:
(1) Defaultsessionconfiguration default session configuration, similar to nsurlconnection standard configuration, use hard disk to store cached data
(2) Ephemeralsessionconfiguration temporary session configuration, compared to the default configuration, this configuration will not be cached, cookies, etc. exist locally, only in memory, so when the program exits, all the data will disappear
(3) Backgroundsessionconfiguration background session configuration, similar to the default configuration, different is to open another thread in the background to process network data
4 , Nsurlsessiontask
n nsurlsession the task of using Nsurlsessiontask to perform network requests specifically
N Nsurlsessiontask supports cancellation, suspension, and recovery of network requests, such as downloading files after a pause and then resuming automatically from the last progress to download
N Nsurlsessiontask can also get the reading progress of the data
Three types of n nsurlsessiontask:
(1) Nsurlsessiondatatask handles general NSData data objects, such as getting JSON or XML returns from the server via get or post, but does not support background fetching
(2) Nsurlsessionuploadtask for uploading files, supporting background upload
(3) Nsurlsessiondownloadtask for downloading files, supporting background download
For example:
#pragma mark-upload avatar with session
-(void) UploadFile
{
1. Nsurl
NSString *urlstring = @ "http://localhost/uploads/test. png";
URLString = [URLString stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
Nsurl *url = [Nsurl urlwithstring:urlstring];
Nsurl *url = [Nsurl urlwithstring:@ "http://localhost/uploads/test. png"];
2. Request
Nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url cachepolicy:0 timeoutInterval:2.0];
Request. HttpMethod = @ "PUT";
Set up user authorization
1> "admin:123456"
NSString *authstr = @ "admin:123456";
2> result = BASE64 encoding of strings (an encoding format commonly used in network transmissions, NSData)
NSData *authdata = [Authstr datausingencoding:nsutf8stringencoding];
NSString *result = [Authdata base64encodedstringwithoptions:0];
3> "Basic result" and the validation string submitted to the server to verify the identity
NSString *authstring = [NSString stringwithformat:@ "Basic%@", result];
Set the value of the HTTP request header, set the user authorization
[Request setvalue:authstring forhttpheaderfield:@ "Authorization"];
3. Session, there is a singleton, which is globally shared
Nsurlsession *session = [Nsurlsession sharedsession];
4. File Upload
Nsurl *bundleurl = [[NSBundle mainbundle] urlforresource:@ "Avatar 1.png" withextension:nil];
All tasks are suspended by default
Nsurlsessionuploadtask *task = [Session uploadtaskwithrequest:request fromfile:bundleurl completionhandler:^ (NSData * Data, Nsurlresponse *response, Nserror *error) {
Upload complete operation
NSLog (@ "%@", response);
}];
[Task resume];
}
5 , through HTTP PUT method to implement the file upload procedure
N Instantiate nsmutableurlrequest and specify HttpMethod as put
N set authorization for the request
(1) Authorization string format: User name: Password
(2) Authorization mode: BASIC Base64 encoded authorization string
(3) Assigning values to the authorization of Httpheaderfield
6 , File upload Request Section
1. URLRequest
Nsurl *url = [Nsurl urlwithstring:@ "Http://localhost/uploads/xxx.png"];
Nsmutableurlrequest *requestm = [nsmutableurlrequest requestwithurl:url cachepolicy:0 timeoutInterval:2.0f];
Requestm.httpmethod = @ "PUT";
Set up user authorization
1> Authorization String (username + password)
NSString *authstr = @ "admin:123456";
2> BASE 64 encoding
NSData *authdata = [Authstr datausingencoding:nsutf8stringencoding];
NSString *base64str = [Authdata base64encodedstringwithoptions:0];
NSString *auth = [NSString stringwithformat:@ "BASIC%@", Base64str];
[Requestm setvalue:auth forhttpheaderfield:@ "Authorization"];
the , HTTP Common methods of
N get gets the specified resource
n POST 2M submits data to the specified resource for processing requests and is used in restful styles for new resources
N head gets the specified resource header information
N PUT replaces the specified resource (browser operation not supported)
n Delete deletes the specified resource
N OPTIONS allows clients to view server performance
n TRACE echo the request received by the server, primarily for testing or diagnostics
N connect reserved for proxy servers that can change connections to pipelines (HTTP proxy usage)
N Hint:
- Due to security considerations, most servers do not open all HTTP request methods
- Put and delete are currently not used much in the country, mostly by post, but in iOS development put is the simplest way to implement file upload
iOS Development urlsession