在 iOS 应用程序中持久化 Cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4597763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Persisting Cookies In An iOS Application?
提问by Alex
I am going to use NSHTTPCookieStorage
in an iOS App to manage cookies that are retrieved from a url, and I understand that it will manage cookies during your application's runtime. However, I was wondering if it's possible to persist cookies after the application has closed. And then read those cookies again when the app is opened again. Does NSHTTPCookieStorage
persist cookies between app uses? Or just during the applications runtime? Do I need to use CoreData
to persist these cookies?`
我将NSHTTPCookieStorage
在 iOS 应用程序中使用来管理从 url 检索的 cookie,我知道它将在您的应用程序运行时管理 cookie。但是,我想知道是否可以在应用程序关闭后保留 cookie。然后在再次打开应用程序时再次读取这些 cookie。NSHTTPCookieStorage
在应用程序使用之间是否保留 cookie?还是只是在应用程序运行时?我需要使用CoreData
这些 cookie 来持久化吗?`
采纳答案by Magnus
You need to re-set the cookies when your app is loaded. I use code like this:
您需要在加载应用程序时重新设置 cookie。我使用这样的代码:
NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:@"MySavedCookies"];
if([cookiesdata length]) {
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
NSHTTPCookie *cookie;
for (cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
and it works just fine.
它工作得很好。
回答by gazreese
You shouldn't need to persist the cookies yourself as suggested in the other answer. NSHTTPCookieStorage
will persist the cookies for you but you need to ensure that the cookies have an expiry date set on the server-side.
您不需要按照其他答案中的建议自行保留 cookie。NSHTTPCookieStorage
将为您保留 cookie,但您需要确保 cookie 在服务器端设置了到期日期。
Cookies without an expiry date are considered 'session only' and will get cleared when you restart the app. You can check the 'session only' situation via a BOOL property in NSHTTPCookie
. This is standard cookie stuff and not something specific to iOS.
没有到期日期的 Cookie 被视为“仅限会话”,并且会在您重新启动应用程序时被清除。您可以通过中的 BOOL 属性检查“仅会话”情况NSHTTPCookie
。这是标准的 cookie 内容,而不是特定于 iOS 的内容。