iPhone: NSHTTPCookie is not saved across app restarts

本文详细介绍了如何在iOS应用重启后保存并重用服务器会话,通过使用NSHTTPCookieStorage和UserDefaults来实现服务器会话的持久化。文章提供了具体的代码示例,包括如何获取和保存服务器会话的cookie,以及如何在应用重启时重新加载和使用这些cookie。同时讨论了是否需要同步UserDefaults以确保数据的一致性和持久性。

iPhone: NSHTTPCookie is not saved across app restarts

 

 

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.

 

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?

 

 

accepted

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

 

Save:

 

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];

    }

 }

Load:

 

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];

}

 

 

do you need to synchronize the nsuserdefaults? – Ninja Jan 10 at 8:52

You only need to synchronize if you need to save them right then. Otherwise they will be saved at some interderminate time later. Here's the doc page: developer.apple.com/library/mac/#documentation/Cocoa/Reference/… – Mike Katz Jan 10 at 18:44


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值