Ios 重新启动手机后,如果应用程序在手机解锁至少一次之前启动,NSHTTPCookie存储将丢失cookies
问题 正如标题所说,我目前遇到了一个问题,Ios 重新启动手机后,如果应用程序在手机解锁至少一次之前启动,NSHTTPCookie存储将丢失cookies,ios,iphone,cookies,nsurlrequest,nsurlsession,Ios,Iphone,Cookies,Nsurlrequest,Nsurlsession,问题 正如标题所说,我目前遇到了一个问题,nshttpcookeestorage在手机重新启动后至少解锁一次之前,在后台初始化我们的应用程序时,会丢失应用程序的cookie 一旦cookie丢失,它们将无法以任何方式恢复,从而迫使用户重新登录以检索一组新的cookie并恢复会话 如果在用户解锁手机后第一次注册应用程序活动,那么一切都像一个魔咒 上下文: 这个问题发生在我们使用NSURLRequest和NSURLSession时 与使用自动cookie处理的ASIHTTP和AFNetworkin
nshttpcookeestorage
在手机重新启动后至少解锁一次之前,在后台初始化我们的应用程序时,会丢失应用程序的cookie
一旦cookie丢失,它们将无法以任何方式恢复,从而迫使用户重新登录以检索一组新的cookie并恢复会话
如果在用户解锁手机后第一次注册应用程序活动,那么一切都像一个魔咒
上下文:
- 这个问题发生在我们使用
和NSURLRequest
时 与使用自动cookie处理的ASIHTTP和AFNetworking一样,也可以 我们得出的结论是,它会影响整个NSURLSession
班级NSHTTPCookieStorage
- 我们的应用程序具有SLC(重要位置更改监控),因此其
在后台自动触发
任何帮助或想法都将不胜感激。从您描述的行为来看,
NSHTTPCookieStorage
使用的底层文件存储的保护似乎已经设置
由于您无法更改存储数据的位置和方式,因此您有两种选择:
UIApplication
的属性,并推迟更新,直到设备解锁。您可以注册设备解锁时收到的通知NSHTTPCookieStorage
类)。但是不要使用NSUSerDefaults
,因为它具有
同样的问题- 使用
权限在磁盘中创建文件nsfileprotectioncompleteentilfirstUserAuthentication
- 在进行任何网络呼叫之前,请检查应用程序是否能够读取该文件。如果是,这意味着手机至少被解锁了一次,所以你可以在不丢失cookies的情况下拨打电话李>
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];
您是否在应用程序重启之间以用户默认值保存和存储cookie?不,我们没有。我们不是手动处理cookies。所有Cookie管理都由NSURLRequest类自动完成。谢谢您提供的信息。我们采取了与你建议的非常相似的方法。我们测试了protectedDataAvailable
功能,但它有一个大问题,即如果手机已锁定,但之前在某个点已解锁,它也会返回NO
。如果手机至少被解锁一次,那么无论手机在网络通话时是否被锁定,cookies都不会丢失,因此这种解决方案实际上阻止了我们在手机被锁定时进行任何行为,这比我们想要的限制要严格得多(当手机被锁定时,我们需要反向行为,以便ap工作)然后,您可能需要创建另一个具有相同保护级别的文件,然后测试该文件的可读性,以确认您的cookie是否可用。编辑-我刚刚看到这是另一个答案中建议的技巧是的,无论如何谢谢你的反馈。很好的帮助