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

查看:92
本文介绍了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不会话?

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的属性字典,然后恢复

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天全站免登陆