iPhone:NSHTTPCookie 不会在应用程序重新启动时保存 [英] iPhone: NSHTTPCookie is not saved across app restarts

查看:32
本文介绍了iPhone:NSHTTPCookie 不会在应用程序重新启动时保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 iPhone 应用程序中,我希望能够在我的应用程序重新启动时重复使用相同的服务器端会话.服务器上的会话由 cookie 标识,每个请求都会发送该 cookie.当我重新启动应用程序时,该 cookie 消失了,我无法再使用相同的会话.

In my iPhone app, I want to be able to reuse the same server-side session when my app restarts. A session on the server is identified by a cookie, which is sent on each request. When I restart the app, that cookie is gone and I can't use the same session anymore.

当我使用 NSHTTPCookieStorage 查找从服务器获取的 cookie 时,我注意到 [cookie isSessionOnly] 返回 YES.我的印象是这就是为什么在我的应用程序重新启动时不保存 cookie 的原因.我该怎么做才能让我的 cookie NOT 仅会话?我必须从服务器发送哪些 HTTP 标头?

What I noticed when I used the NSHTTPCookieStorage to look up the cookie I got from the server, is that [cookie isSessionOnly] returns YES. I get the impression that this is why cookies are not saved across restarts of my app. What would I have to do to make my cookie NOT session only? What HTTP headers do I have to send from the server?

推荐答案

您可以通过保存 cookie 的属性字典来保存 cookie,然后在重新连接之前恢复为新的 cookie.

You can save the cookie by saving its properties dictionary and then restoring as a new cookiebefore you go to re-connect.

保存:

NSArray* allCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:URL]];
for (NSHTTPCookie *cookie in allCookies) {
    if ([cookie.name isEqualToString:MY_COOKIE]) { 
        NSMutableDictionary* cookieDictionary = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] dictionaryForKey:PREF_KEY]];
        [cookieDictionary setValue:cookie.properties forKey:URL];
        [[NSUserDefaults standardUserDefaults] setObject:cookieDictionary forKey:PREF_KEY];
    }
 }

加载:

NSDictionary* cookieDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:PREF_KEY];
NSDictionary* cookieProperties = [cookieDictionary valueForKey:URL];
if (cookieProperties != nil) {
    NSHTTPCookie* cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    NSArray* cookieArray = [NSArray arrayWithObject:cookie];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookieArray forURL:[NSURL URLWithString:URL] mainDocumentURL:nil];
}

这篇关于iPhone:NSHTTPCookie 不会在应用程序重新启动时保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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