iOS 获取准确的Cookie

项目上需要将服务器返回的cookie上的sid项保存到本地用于维护一个长登陆状态
网上获取Cookie的方法一般是这样的

  let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
                    var sid: String?
                    let cookieArray = cookieStorage.cookies 
                   
                    for cookie in cookieArray {
                        if cookie.name == "sid" {
                            //获取cookie的sid对应的值
                            sid = cookie.value
                            break
                        }
                    }

但是cookie数组里含有name为sid的会有多项,这样无法精确获取一个cookie,后来知道NSHTTPURLResponse里有一项allHeaderFields属性,allHeaderFields是一个[string:AnyObject]类型的字典,里面是原始Http响应头部,打印一下,

[Server: nginx, Set-Cookie: sid=6udoy4al4bk8vk8qr0x0jq6oninx9f8f; expires=Mon, 07-Aug-2017 08:41:58 GMT; Max-Age=31536000; path=/, Content-Type: application/json, Transfer-Encoding: Identity, Proxy-Connection: Keep-alive, Date: Sun, 07 Aug 2016 08:41:58 GMT, Content-Encoding: gzip, Vary: Accept-Encoding]

里面有一项"Set-Cookie",是一个字符串

Set-Cookie: sid=6udoy4al4bk8vk8qr0x0jq6oninx9f8f; expires=Mon, 07-Aug-2017 08:41:58 GMT; Max-Age=31536000; path=/

这样我们就可以写个函数截取这个sid的内容了
随手写了

//对应上面的打印内容 cookieStr为"sid=6udoy4al4bk8vk8qr0x0jq6oninx9f8f; expires=Mon, 07-Aug-2017 08:41:58 GMT; Max-Age=31536000; path=/"
//name为"sid"
 class func getSetCookieOneContentWithName(cookieStr: String,name:String) -> String {
        let cookieTempStr = cookieStr as NSString
        if cookieTempStr.containsString(name) == false
        {
            return ""
        }
        let range = cookieTempStr.rangeOfString(name)
        //加1是等号
        let contentStart = range.location+range.length+1
        var length = 0
        for i in contentStart..

好啦,这样就可以准确获得一个网络请求回调的cookie啦

你可能感兴趣的:(iOS 获取准确的Cookie)