ios - Swift: How to remember cookies for further http requests -
i working on login application. after successful login response comes cookie data.
how can use/save data future requests?
starters trying save in nshttpcookiestorage
. 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? { 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 not parse json: '\(jsonstr)'") } else { print("everything looks good: \(responsedata)") self.setcookies(responsedata!) self.shouldperformseguewithidentifier("showhomecontroller", sender: self) } } task?.resume()
save cookie method
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) 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())") } } }
error:
cannot invoke 'cookieswithresponseheaderfields' argument list of type '([nsobject : anyobject], forurl: nsurl)'
if realize usage of cookie, server has send header set-cookie in response client request.
https://en.wikipedia.org/wiki/http_cookie#setting_a_cookie
if use nsurlsession , nsurlconfiguration defaultconfiguration or backgroundsession, dont have make changes save cookie. system itself.
from nsurlsessionconfiguration, httpcookiestorage documentation,
the cookie store storing cookies within session. property determines cookie storage object used tasks within sessions based on configuration. disable cookie storage, set property nil. default , background sessions, default value shared cookie storage object. ephemeral sessions, default value private cookie storage object stores data in memory only, , destroyed when invalidate session.
so, did small experiment read cookie google.com , here how 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()
with prints following,
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 has property httpcookieacceptpolicy, quotes following:
a policy constant determines when cookies should accepted. property determines cookie accept policy tasks within sessions based on configuration. default value nshttpcookieacceptpolicyonlyfrommaindocumentdomain. can change of constants defined in nshttpcookieacceptpolicy enumerated type. if want more direct control on cookies accepted, set value nshttpcookieacceptpolicynever , use allheaderfields , cookieswithresponseheaderfields:forurl: methods extract cookies url response object yourself.
so, states if want able manipulate cookie ourself, should set policy nshttpcookieacceptpolicynever , use method allheaderfields , cookieswithresponseheaderfields:forurl: extracting cookies , saving.
here how 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) } } }
even then, not need set cookie storage yourself. notice httpcookiestorage documentation, says using default or background sessions uses shared storage unless set nil httpcookiestorage property or set other storage.
so, if log default storage cookies, cookies above,
print(nshttpcookiestorage.sharedhttpcookiestorage().cookies)
it seems possible define own custom storage shared cookie storage, can used across extensions , applications ios 9.
so, dont think necessary set cookie since there built in mechanism so, unless need precise control on cookie properties.
Comments
Post a Comment