iPhone: NSHTTPCookie is not saved across app restarts

后端 未结 7 552
梦如初夏
梦如初夏 2020-12-01 05:14

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 requ

7条回答
  •  旧巷少年郎
    2020-12-01 05:58

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

提交回复
热议问题