Swift:如何记住进一步的http请求的cookie [英] Swift: How to remember cookies for further http requests

查看:1969
本文介绍了Swift:如何记住进一步的http请求的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用登录应用程序。成功登录后,系统会回复Cookie数据。
如何使用/保存此数据以用于将来的请求?

对于初学者,我尝试将其保存在 NSHTTPCookieStorage 。但这也不行。 $ b $bÁ
登录方式(部分):

I am working on a login application. After successful login response comes back with cookie data.
How can I use/save this data for my future requests?
For starters I am trying to save it in NSHTTPCookieStorage. But that is also not working.
Login Method(partial):

let task = session.dataTaskWithRequest(request) { (data, responseData, error) -> Void in
            if let response = responseData as? NSHTTPURLResponse {
                statusCode = response.statusCode
                print("Response code: \(statusCode)")
            }

            var json: NSDictionary?
            do {
                json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
            } catch {
                print(error)
                err = error
            }

            if(statusCode != 200) {

                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
            else {

                print("Everything Looks good: \(responseData)")
                self.setCookies(responseData!)
                self.shouldPerformSegueWithIdentifier("showHomeController", sender: self)

            }
        }

        task?.resume()

储存Cookie方法

private func setCookies(response: NSURLResponse) {
        if let httpResponse = response as? NSHTTPURLResponse {
            let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(httpResponse.allHeaderFields, forURL: response.URL!) as! [NSHTTPCookie]
            NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: response.URL!, mainDocumentURL: nil)
            for cookie in cookies {
                var cookieProperties = [String: AnyObject]()
                cookieProperties[NSHTTPCookieName] = cookie.name
                cookieProperties[NSHTTPCookieValue] = cookie.value()
                cookieProperties[NSHTTPCookieDomain] = cookie.domain
                cookieProperties[NSHTTPCookiePath] = cookie.path
                cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: cookie.version)
                cookieProperties[NSHTTPCookieExpires] = NSDate().dateByAddingTimeInterval(31536000)

                let newCookie = NSHTTPCookie(properties: cookieProperties)
                NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)

                println("name: \(cookie.name) value: \(cookie.value())")
            }
        }
    }

/ strong>

Error:

Cannot invoke 'cookiesWithResponseHeaderFields' with an argument list of type '([NSObject : AnyObject], forURL: NSURL)'


推荐答案

如果你意识到cookie的使用,必须发送头set-cookie以响应客户端请求。

If you realize the usage of cookie, the server has to send the header set-cookie in response to the client request.

https://en.wikipedia.org/wiki/HTTP_cookie #Setting_a_cookie

如果您将NSURLSession和NSURLConfiguration与defaultConfiguration或backgroundSession配合使用,则不必进行任何更改以保存Cookie。系统本身。

If you use NSURLSession and NSURLConfiguration with defaultConfiguration or backgroundSession, you dont have to make any changes to save the cookie. The system does it by itself.

来自NSURLSessionConfiguration,HTTPCookieStorage文档,

From NSURLSessionConfiguration, HTTPCookieStorage documentation,


本届会议。此
属性确定基于此配置的
会话中的所有任务使用的cookie存储对象。要禁用Cookie存储,请将
此属性设置为nil。对于默认和后台会话,默认
值是共享cookie存储对象。对于临时会话,
默认值是一个私人cookie存储对象,它只在
内存中存储数据,并且在会话失效时被销毁。

The cookie store for storing cookies within this session. This property determines the cookie storage object used by all tasks within sessions based on this configuration. To disable cookie storage, set this property to nil. For default and background sessions, the default value is the shared cookie storage object. For ephemeral sessions, the default value is a private cookie storage object that stores data in memory only, and is destroyed when you invalidate the session.

所以,我做了一个小实验,从google.com读取cookie,这里是它的外观,

So, I did a small experiment to read the cookie from google.com and here is how it looks like,

 private func setCookies(response: NSURLResponse) {
        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(response.URL!)
        print(cookies)
    }

    let request = NSURLRequest(URL: NSURL(string: "https://google.com")!)

    configuration = NSURLSessionConfiguration.defaultSessionConfiguration()

    session = NSURLSession(configuration: configuration)

    let task = session.dataTaskWithRequest(request) { data, response, error -> Void in
        if error == nil {
            self.setCookies(response!)
        }
    }
    task?.resume()

打印以下内容:

Optional([<NSHTTPCookie version:0 name:"NID" value:"69=j740tX4kU9JCWniPgXmngbD9ANWpzntszGg7Becz8FXCImLiVc3FmoHKdV-iOdd_PSCQeuVecwK6cyNfMOEW0gSz96CMEthN5uPZrR0J03sUKFuoRg4fO5A2ybwY6U_K" expiresDate:2016-01-15 22:01:36 +0000 created:2015-07-16 22:01:36 +0000 sessionOnly:FALSE domain:".google.fi" path:"/" isSecure:FALSE>, <NSHTTPCookie version:0 name:"PREF" value:"ID=1111111111111111:FF=0:TM=1437084096:LM=1437084096:V=1:S=TOU92HOWgdBrA6yl" expiresDate:2017-07-15 22:01:36 +0000 created:2015-07-16 22:01:36 +0000 sessionOnly:FALSE domain:".google.fi" path:"/" isSecure:FALSE>])

NSURLSessionConfiguration还有一个属性HTTPCookieAcceptPolicy引用以下内容:

NSURLSessionConfiguration also has a property HTTPCookieAcceptPolicy, which quotes the following:


决定何时接受Cookie的策略常量。
此属性基于此配置确定
会话中的所有任务的cookie接受策略。默认值为
NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain。您可以将其
更改为NSHTTPCookieAcceptPolicy
枚举类型中定义的任何常量。如果你想更直接地控制什么cookie是
接受,设置这个值为NSHTTPCookieAcceptPolicyNever然后使用
allHeaderFields和cookiesWithResponseHeaderFields:forURL:
方法自己从URL响应对象中提取cookie。

A policy constant that determines when cookies should be accepted. This property determines the cookie accept policy for all tasks within sessions based on this configuration. The default value is NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain. You can change it to any of the constants defined in the NSHTTPCookieAcceptPolicy enumerated type. If you want more direct control over what cookies are accepted, set this value to NSHTTPCookieAcceptPolicyNever and then use the allHeaderFields and cookiesWithResponseHeaderFields:forURL: methods to extract cookies from the URL response object yourself.

因此,它声明如果我们想要能够自己操作cookie,我们应该将策略设置为NSHTTPCookieAcceptPolicyNever,并使用方法allHeaderFields和cookiesWithResponseHeaderFields:forURL:用于提取cookie并保存。

So, it states that if we want to be able to manipulate the cookie by ourself, we should set the policy to NSHTTPCookieAcceptPolicyNever and use the method allHeaderFields and cookiesWithResponseHeaderFields:forURL: for extracting the cookies and saving.

这里是你如何做这个例子。

Here is how you would do it for this example.

let request = NSURLRequest(URL: NSURL(string: "https://google.com")!)

configuration = NSURLSessionConfiguration.defaultSessionConfiguration()

configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Never

session = NSURLSession(configuration: configuration)

let task = session.dataTaskWithRequest(request) { data, response, error -> Void in
    if error == nil {
        self.setCookies(response!)
    }
}
task?.resume()

}

private func setCookies(response: NSURLResponse) {

    if let httpResponse = response as? NSHTTPURLResponse {
        if let headerFields = httpResponse.allHeaderFields as? [String: String] {
            let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: response.URL!)
            print(cookies)
        }
    }
}

即使这样,您也不需要自己将Cookie设置为存储。注意HTTPCookieStorage文档,它说,使用默认或后台会话始终使用共享存储,除非您将nil设置为HTTPCookieStorage属性或设置一些其他存储。

Even then, you do not need to set the cookie to storage by yourself. Notice the HTTPCookieStorage documentation, it says that using default or background sessions always uses the shared storage unless you set nil to HTTPCookieStorage property or set some other storage.

因此,如果您只需记录默认的存储Cookie,就会从上面获取所有Cookie,

So, if you simply log the default storage cookies, you will get all the cookies from above,

print(NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies)

像是可以定义自己的自定义存储共享cookie存储,可以在iOS 9的扩展和应用程序中使用。

It seems like it is possible to define your own custom storage shared cookie storage, which can be used across extensions and applications with iOS 9.

所以,我不认为这是真的有必要自己设置cookie,因为已经有一个内置的机制,这样做,除非你需要真正的精确控制cookie属性。

So, I dont think it is really necessary to set cookie by yourself since there is already a built in mechanism to do so, unless you need really a precise control over to the cookie properties.

这篇关于Swift:如何记住进一步的http请求的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆