Does NSURLConnection automatically persist cookies sent from server?

筅森魡賤 提交于 2019-12-03 07:14:11

问题


I logged into my tornado backend from ios and sent back a secure_cookie and i noticed that i could also request other information as long as i validated the secure_cookie that i set. How long does NSURLConnection persist the cookie or will the cookie be deleted once they close the app?

This is mentioned in the Apple docs:

The URL loading system automatically sends any stored cookies appropriate for an NSURLRequest. unless the request specifies not to send cookies.


回答1:


A few facets to your question.

To start with, NSURLConnection will, by default, manage cookies based on the settings for the device. It will save the cookies to the store and send them as appropriate (when the domain matches an existing cookie). This means if you make a request from a URL with a cookie saved in the cookie store, it will be sent. This explains the behavior you mentioned. Generally, with the default settings, the cookie will persist for quite a while.

This initial statement, however, maybe is not helpful for your needs. I am assuming you may want to have control over the expiration of (or keep around "forever") this secure_cookie field so your app does not have to authenticate further in the future.

In this case, NSHTTPCookieStorage is the place to look. This class will allow you to both retrieve:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://example.com"]]

and set:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie] (plus setting up the cookie dictionary object)

Based on experience and the feedback of others online, you should note that the cookie storage is not always 100% reliable. If you would like to be sending a specific cookie and value to the server, you should store that value with your app (prefs or Core Data, for example), and reset the cookie with the appropriate NSHTTPCookieStorage at each startup.




回答2:


You have to look into the cookie cache management from here This will help you to better understand how the caching for cookie is handled.

There is another very good description, where it's mentioned that you can get the cookie from headers fields and then you have full control of it. If you want, store and use when application launched again.

I hope this should help you to solve it.



来源:https://stackoverflow.com/questions/12022541/does-nsurlconnection-automatically-persist-cookies-sent-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!