Detailed user data storage processing in IOS app development session and Coockie _ios

Source: Internet
Author: User
Tags http request


Nsurlsession
after iOS7, nsurlsession as the system recommended HTTP request framework, in the case of the foreground request, nsurlsession and nsurlconnection are not significantly different, for background requests, Nsurlsession's more flexible advantages will be evident.
type of 1.NSURLSession collection



The Nsurlsession class provides the session type in 3:



(1) Default type: Provides the method of the foreground request, supports the configuration cache, the credential and so on.



(2) Ephemeral type: Immediate type of request, no caching, credentials, etc.



(3) Background: Background type, support to complete the request task in the background.



Type of 2.NSURLSession task



Request tasks added in Nsurlsession support 3 type:



(1) Data task: Use NSData object to send and obtain data, generally used for short data task.



(2) Download task: Download data from the file, support the background download.



(3) Upload task: File The form of uploading data to support the background upload.



3. Create and configure Nsurlsession:



By configuring and creating Nsurlsession with the Nsurlsessionconfiguration class object, the sample code for creating and matching nsurlsession is as follows:


   //default type
    nsurlsessionconfiguration * defaultconfiguration = [ Nsurlsessionconfiguration Defaultsessionconfiguration];
   //immediate type
    nsurlsessionconfiguration * ephemeralconfiguration = [ Nsurlsessionconfiguration Ephemeralsessionconfiguration];
   //Background type
    nsurlsessionconfiguration * backgroundconfiguration = [ Nsurlsessionconfiguration backgroundsessionconfigurationwithidentifier:@ "SessionId"];
   
   //Create and set session
    nsurlsession * defaultsession = [ Nsurlsession Sessionwithconfiguration:defaultconfiguration];
    nsurlsession * ephemeralsession = [nsurlsession sessionwithconfiguration: Ephemeralconfiguration];
    nsurlsession * backgroundsession = [nsurlsession sessionwithconfiguration: Backgroundconfiguration];
Nsurlsessionconfiguration can also configure parameters such as caching, network mode, etc.


4. Two ways to use nsurlsession for network requests



Nsurlsession has two ways to request network data, one is to get network data through block, one is to get network data through proxy callback. The request code through block is as follows:



   //Create Session Configuration Object
    nsurlsessionconfiguration * defaultconfiguration = [Nsurlsessionconfiguration defaultsessionconfiguration];
   //Create Request Object
    nsurlrequest * request = [Nsurlrequest Requestwithurl:[nsurl urlwithstring:@ "http://www.baidu.com"]];
   //Create Session Object
    nsurlsession * defaultsession = [nsurlsession Sessionwithconfiguration:defaultconfiguration];
   //Add Tasks
    nsurlsessiontask * task= [defaultsession datataskwithrequest: Request completionhandler:^ (NSData * _nullable data, Nsurlresponse * _nullable response, Nserror * _nullable error) {
        NSLog (@ "%@", data);
   }];
   //Start Task
    [task resume];
Requests using proxy callbacks require compliance with the following protocol:



@interface ViewController ()<NSURLSessionDataDelegate>
@end
Modify the request code as follows:



    NSURLSessionConfiguration * defaultConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    NSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];



    NSURLSessionTask * task= [defaultSession dataTaskWithRequest:request];
    [task resume];
Implement the Proxy method as follows:



// Start receiving data
-(void) URLSession: (NSURLSession *) session dataTask: (NSURLSessionDataTask *) dataTask didReceiveData: (NSData *) data {
     NSLog (@ "=======% @", data);
}
// End of accepting data
-(void) URLSession: (NSURLSession *) session task: (NSURLSessionTask *) task didCompleteWithError: (NSError *) error {
     NSLog (@ "Completion: error% @", error);
}

5. Download tasks in background



Nsurlsession's biggest advantage is its background download flexibility, using the following code for background data download:



 nsurlsessionconfiguration * backgroundconfiguration = [nsurlsessionconfiguration backgroundsessionconfigurationwithidentifier:@ "Com.zyprosoft.backgroundsession"];
    nsurlrequest * request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http:// Www.baidu.com "]];
    nsurlsession *  backgroundsession   = [nsurlsession sessionwithconfiguration: Backgroundconfiguration delegate:self Delegatequeue:nil];
    [[Backgroundsession Downloadtaskwithrequest:request]resume];
listens to download progress in the following callback method:



- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"######");
}
If you click the Home button in the download process to enable the application to enter the background, Nsurlsession's related proxy method will no longer be recalled, but the download task is still in progress, when the background download is completed and appdelegate interaction, will call the following methods in Appdelegate:



-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
    NSLog(@"1111");
}
The application then invokes the following method of the Nsurlsesstion proxy in the background to notify the download result:



// This method will be called regardless of success or failure
-(void) URLSession: (NSURLSession *) session task: (NSURLSessionTask *) task didCompleteWithError: (NSError *) error {
     NSLog (@ "Completion: error% @", error);
}
// This method will only be called if the download is successful. The file is placed in the location.

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
   
}
Finally, the following methods of Nsurlsesstion are called:



-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{
   
    NSLog(@"All tasks are finished");
   
}






Cookies



Cookies are Web sites to be the terminal identity, stored in the terminal local user credentials information. The fields and meanings in the cookie are defined by the service side. For example, when a user logs on to a Web site, the server returns the cookie information to the terminal and the terminal saves the information, and the terminal sends the saved cookie message to the server the next time it visits the site. The server determines whether this user can log on automatically based on whether the cookie information is valid.



Two classes for cookie management in iOS:



The HTTP network request cookie Management in iOS is mainly handled by two classes, one class is Nshttpcookiestorage class and the other is Nshttpcookie class.



1.NSHTTPCookieStorage



The Nshttpcookiestorage class takes a single example of the design pattern, which manages cookie information for all HTTP requests, commonly used in the following ways:


Get a single Instance object
+ (Nshttpcookiestorage *) sharedhttpcookiestorage;
All cookie data arrays where Nshttpcookie objects are stored
@property (Nullable, ReadOnly, copy) Nsarray<nshttpcookie *> *cookies;
Manually set up a cookie data
-(void) Setcookie: (Nshttpcookie *) cookie;
Delete a cookie message
-(void) Deletecookie: (Nshttpcookie *) cookie;
Delete all cookie information after a time iOS8 available
-(Nullable Nsarray<nshttpcookie *> *) Cookiesforurl: (Nsurl *) URL;
Get all cookie data for a particular URL
-(void) Removecookiessincedate: (NSDate *) Date ns_available (10_10, 8_0);
Set a cookie for a specific URL
-(void) Setcookies: (Nsarray<nshttpcookie *> *) Cookies Forurl: (Nullable Nsurl *) URL Maindocumenturl: (Nullable Nsurl *) Maindocumenturl;
Receive protocol for cookie data
/*
Enumerated below:
typedef ns_enum (Nsuinteger, Nshttpcookieacceptpolicy) {
nshttpcookieacceptpolicyalways,//Receive all cookie information
nshttpcookieacceptpolicynever,//does not receive all cookie information
nshttpcookieacceptpolicyonlyfrommaindocumentdomain//only receive cookie information for the main document field
};
*/
@property Nshttpcookieacceptpolicy Cookieacceptpolicy;
The two notifications below the system are related to cookie management:


// Notification sent when the protocol for receiving cookie data changes
FOUNDATION_EXPORT NSString * const NSHTTPCookieManagerAcceptPolicyChangedNotification;
// Notification sent when the managed cookie data changes
FOUNDATION_EXPORT NSString * const NSHTTPCookieManagerCookiesChangedNotification;



2.NSHTTPCookie



Nshttpcookie is a specific HTTP request cookie data object, where the property method is as follows:


The following two methods are used for object creation and initialization through the dictionary for key value setting
-(Nullable Instancetype) Initwithproperties: (nsdictionary<nsstring *, id> *) properties;
+ (Nullable Nshttpcookie *) Cookiewithproperties: (nsdictionary<nsstring *, id> *) properties;
Returns a dictionary in cookie data that can be used to add HTTP header fields
+ (nsdictionary<nsstring *, nsstring *> *) requestheaderfieldswithcookies: (Nsarray<nshttpcookie *> *) Cookies
Resolves the cookie data from the specified response header and URL address
+ (Nsarray<nshttpcookie *> *) Cookieswithresponseheaderfields: (nsdictionary<nsstring *, NSString *> *) Headerfields Forurl: (Nsurl *) URL;
Dictionary of properties in cookie data
@property (Nullable, ReadOnly, copy) nsdictionary<nsstring *, id> *properties;
The version of the request response
@property (readonly) Nsuinteger version;
Request the appropriate name
@property (readonly, copy) NSString *name;
Request the appropriate value
@property (readonly, copy) NSString *value;
Expiration time
@property (Nullable, ReadOnly, copy) NSDate *expiresdate;
The requested domain name
@property (readonly, copy) NSString *domain;
The path of the request
@property (readonly, copy) NSString *path;
Whether it is a secure transmission
@property (readonly, getter=issecure) BOOL secure;
Whether to send only HTTP services
@property (readonly, getter=ishttponly) BOOL HttpOnly;
The document for the response
@property (Nullable, ReadOnly, copy) NSString *comment;
The corresponding document URL
@property (Nullable, ReadOnly, copy) Nsurl *commenturl;
Service Port List
@property (Nullable, ReadOnly, copy) Nsarray<nsnumber *> *portlist;




Related Article

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.