2010-06-27 44 views
1

我的iPhone应用程序有一个UIWebView,用于加载包含设置Cookie的JavaScript的页面。看来,如果我设置了一个cookie并在10-15秒内退出应用程序,那么该cookie永远不会被保存,但是如果我设置了cookie,请等待10-15秒,然后退出该应用程序,cookie将被保存。iPhone应用程序Cookie延迟

任何人都有任何关于为什么他们是延迟的信息,以及如何去立即保存cookie。

回答

4

我能够想出的唯一解决方法是在应用程序终止之前将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]; 
    } 
1

有这个相同的问题。延迟实际上是从我的测试30秒。我失去了几天试图调试。可能有办法通过在30秒过去之前手动重新保存cookie来解决这个问题,但我还没有尝试过。

+0

必须有同步的饼干的方式 – AlBeebe 2011-01-19 14:24:54

+1

有一个[私有API(http://stackoverflow.com/a/10054438/1872297)来做到这一点。 我填写了rdar:// 13293418([openradar](http://openradar.appspot.com/radar?id=2776403))要求将此API公开;你可以填写一个副本给它一些重量。 – Kemenaran 2013-02-26 10:01:56