iPhone 应用程序 Cookie 延迟

AlB*_*ebe 1 iphone cookies

我的 iPhone 应用程序有一个 UIWebView,它加载一个包含设置 cookie 的 javascript 的页面。似乎如果我设置 cookie 并在 10-15 秒内退出应用程序,那么 cookie 永远不会保存,但是如果我设置 cookie,等待 10-15 秒然后退出应用程序,cookie 就会被保存。

任何人都知道为什么会出现延迟以及如何立即保存 cookie。

AlB*_*ebe 5

我能想到的唯一解决方法是在应用程序终止之前将 cookie 保存到用户默认值。当应用程序打开时,检查用户默认设置,取出 cookie,并将它们重写到 cookie 存储中。它可以工作,但如果您的应用程序被强制终止,那么它就不会真正起作用。

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

    // Load the saved cookies
    NSDate *currentDate = [NSDate date];
    NSTimeInterval expirationAmount = 5 * 365 * 24 * 60 * 60;
    NSDate *expirationDate = [currentDate dateByAddingTimeInterval:expirationAmount];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    for (id theKey in [defaults dictionaryRepresentation]) {
        if ([theKey hasPrefix:@"cookie:"]) {
            [self setCookie:[theKey substringFromIndex:7] value:[defaults objectForKey:theKey] expiration:[expirationDate description] domain:urlDomain];
        }
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
  // Save the cookies to the user defaults
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  NSArray* theCookies = [cookieStorage cookies];
 for(NSHTTPCookie *myStr in theCookies) {
    [defaults setValue:[myStr value] forKey:[NSString stringWithFormat:@"cookie:%@", [myStr name]]];
     }
     [[NSUserDefaults standardUserDefaults] synchronize];
   }
Run Code Online (Sandbox Code Playgroud)