简体   繁体   English

在iOS应用程序中保留Cookie?

[英]Persisting Cookies In An iOS Application?

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. 我将在iOS应用程序中使用NSHTTPCookieStorage来管理从URL检索到的cookie,我知道它将在应用程序的运行时管理cookie。 However, I was wondering if it's possible to persist cookies after the application has closed. 但是,我想知道在应用程序关闭后是否可以保留cookie。 And then read those cookies again when the app is opened again. 然后在再次打开应用程序时再次阅读这些cookie。 Does NSHTTPCookieStorage persist cookies between app uses? NSHTTPCookieStorage是否在应用程序使用之间保留cookie? Or just during the applications runtime? 或者只是在应用程序运行时? Do I need to use CoreData to persist these cookies?` 我是否需要使用CoreData来保存这些cookie?`

You shouldn't need to persist the cookies yourself as suggested in the other answer. 您不应该像其他答案中所建议的那样自己坚持使用cookie。 NSHTTPCookieStorage will persist the cookies for you but you need to ensure that the cookies have an expiry date set on the server-side. NSHTTPCookieStorage将为您保留cookie,但您需要确保cookie在服务器端设置了到期日期。

Cookies without an expiry date are considered 'session only' and will get cleared when you restart the app. 没有过期日期的Cookie被视为“仅限会话”,并会在您重新启动应用时清除。 You can check the 'session only' situation via a BOOL property in NSHTTPCookie . 您可以通过NSHTTPCookie的BOOL属性检查“仅会话”情况。 This is standard cookie stuff and not something specific to iOS. 这是标准的cookie内容,而不是iOS特有的内容。

You need to re-set the cookies when your app is loaded. 您需要在加载应用时重新设置Cookie。 I use code like this: 我使用这样的代码:

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. 它工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM