Using Swift to read cookie content

Source: Internet
Author: User


Objective


In an HTTP request, we often refer to the URL of the GET request Param,post http Body,response Json, which is a standard rest API element that comes standard.



In some security-validated APIs, cookies are often involved. When the user logs in successfully, the server writes a Set-cookie field in the response header to identify the user's login (authorization) Success, and the client browser receives the cookie field locally on the client. When the client requests the API again, it will bring the cookie value in the request header to tell the server: Hi, I have authorized it, my cookie value is xxx, I now want to read some information, please release ~


Network requests in iOS


A complete network request, you need to determine the request URL, take the parameters, then send the request, and then receive response, processing response Data.



In iOS, each corresponds to the following:


// Request URL
NSURL

// A complete Request object
NSURLRequest

// The main operator sending the connection request
NSURLConnection

// Response containing returned data
NSURLResponse


Here is a simple GET request code:


let request = NSURLRequest (URL: NSURL (string: "http://devonios.com")!)
  NSURLConnection.sendAsynchronousRequest (request, queue: NSOperationQueue ()) {(response, nsData, error)-> Void in
             // Process the returned data nsData
}
Observing cookies in HTTP requests using the PAW program


Paw is a great program for testing the HTTP REST API under an OS X system. We use it to see how a request and cookie in response behaves.



Cookies in the response:






The PAW program is also very intelligent, and when a response contains a cookie, it is automatically saved to the default cookie jar.



Here you can see the cookie saved by paw:






Cookie data saved:






The cookie has been saved, so when we send a request again, we will automatically bring a cookie:





Where are the cookies?


You may find that there are no cookie-related methods or properties in Nsurlrequest and Nsurlresponse.



Don't wonder. Because iOS has designed a separate class for us to manage cookie data:nshttpcookiestorage, where one cookie data corresponds to a Nshttpcookie class.



Nshttpcookie is the encapsulation of a cookie data so that we can read the cookie content.



In fact, by default, we can not control the cookie, if the response with Cookie,ios will automatically call Nshttpcookiestorage, the cookie data saved. When there is a new request, Nsurlrequest will automatically bring the corresponding cookie data.



But, the point is, I want to read the cookie, I want to determine the value of the cookie? How do I manually insert a cookie in the request?


iOS security factors, cookies are not shared between apps.
Nshttpcookiestorage reading Cookies


First we need to get the storage to store cookie data:


public class func GetCookieStorage()->NSHTTPCookieStorage{
       return NSHTTPCookieStorage.sharedHTTPCookieStorage()
 }


With storage, it's easy to get a cookie:


public class func GetCookieArray()->[NSHTTPCookie]{
    
    let cookieStorage = GetCookieStorage()
    let cookieArray = cookieStorage.cookies
    if let arr = cookieArray{
        return cookieArray as! [NSHTTPCookie]
    }
    else{
        return []
    }
}





In this func, we get all cookies by using the cookie object of Nshttpcookiestorage, which is an array containing the Nshttpcookie.



Pause, what the hell is Nshttpcookie? What properties and methods does it have, and how do I read the cookie value? Don't be afraid, it's time for our dash big God to play!



See the article about dash introduction



Open our dash, enter Nshttpcookie in the upper-left corner, then this is it:






No difficulty at all:


/// get cookie value
public class func GetCookieByName (let cookieName: String)-> String?
{
     let cookieArray: [NSHTTPCookie] = GetCookieArray ()
     var value: String?
     if cookieArray.count> 0
     {
         for cookie in cookieArray
         {
             if cookie.name == cookieName
             {
                 value = cookie.value
                 break
             }
         }
     }
     return value
} 
In this func, we can get the corresponding value by passing a cookie name.


about how to read the cookie in iOS so it's over, very simple.


Resources


Http://stackoverflow.com/questions/2053568/managing-http-cookies-on-iphone



Tips



This article consists of Wp2osc Import, original link: http://devonios.com/get-cookie.html



because the Oschina OPENAPI automatically filters the IMG tag when processing the content parameter, the picture cannot be displayed, See .



Using Swift to read cookie content


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.