iPhone App Cookie Delay
My iPhone app has a UIWebView that loads a page containing javascript that sets a cookie. It seems that if i set a cookie and exit the app within 10-15 seconds then the cookie is never saved, h开发者_如何学Pythonowever if i set the cookie, wait 10-15 seconds THEN exit the app, the cookie is saved.
Anyone have any info about why their is a delay and how to go about having the cookies saved immediately.
The only workaround i was able to come up with is to save the cookies to the user defaults right before the app terminates. When the app is opened, go through the user defaults, pull out the cookies, and rewrite them to the cookie storage. It works but if your app is forcefully terminated then it doesnt really.
- (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];
}
Having this same problem. The delay is actually 30 seconds exactly from my tests. I lost a couple days trying to debug this. There might be a way to work around this by manually re-saving the cookies before the 30 seconds has elapsed, but I haven't tried this yet.
精彩评论