Seems that iOS is having this same issue but with cookies stored on NSHTTPCookieStorage.
I've already created a radar so feel free to add more so this issue is pushed up a bit in the queue. Radar number is 16237165.
In the meanwhile, you can perform the following workarounds:
Handle cookies manually (aka not rely on iOS automatically managing cookies and storing them in the
NSHTTPCookieStorage
class). But DON'T useNSUSerDefaults
because its having the same issue.Prevent all network activity before phone has been unlocked at least once. This is the option we took and we did the following:
- Create a file in disk with the
NSFileProtectionCompleteUntilFirstUserAuthentication
permission. - Before making any network call, check if the app is able to read that file. If it is, it means phone was unlocked at least once, so you are good to do the call without loosing cookies.
- Create a file in disk with the
Here is a code sample:
static BOOL phoneIsUnlocked = NO;
//If this var is true, then avoid re checking if file has permissions (Cause if it was granted permissions once, it will have access now)
if(phoneIsUnlocked) return phoneIsUnlocked;
//If phone has never been unlocked, prevent all networking stuff just to make sure cookies are not lost due to an ios7 bug.
//Creates a file with NSFileProtectionCompleteUntilFirstUserAuthentication permissions. If the app is able to read it, it means the phone was unlocked at least once after a reboot.
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"a.secure"];
//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
[[NSFileManager defaultManager] createFileAtPath:fileName
contents:[@"secure" dataUsingEncoding:NSUTF8StringEncoding]
attributes:[NSDictionary dictionaryWithObject:NSFileProtectionCompleteUntilFirstUserAuthentication
forKey:NSFileProtectionKey]];
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:fileName];
phoneIsUnlocked = file != nil; //If file is not nil, the phone has been unlocked
[file closeFile];