NSHTTPCookies refuse to be deleted

痞子三分冷 提交于 2019-12-29 05:27:07

问题


I need a log out button for my app, I have the below code:

        while ([[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] count] != 0) {
            for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
            }
        }

(the while is just there to make sure they get deleted, it only runs once however)

If I NSLog the description of shared cookie storage after the above code it outputs that the array is empty. However I terminate the app or just close it, and then NSLog the description of the shared cookie storage the first thing after the app starts, all the cookies are still there.

I have tried setting Cookie to nil in the for loop, and even tried sending dealloc to the cookies (I know you shouldn't do that but I'm now trying anything)


回答1:


The problem seems to be that the cookies are cached and not saved out to a file immediately.

I made a sample project to reproduce this issue — and found that it would only occur when the app receives a SIGKILL signal, like when the debugger is stopped from within Xcode. In my experiments, unhandled exceptions, crashes, exit() and abort() don't cause NSHTPPCookieStorage to loose data.

As this looks like a debugging-only issue (it only occurs when using the debugger), I closed the radar I filled previously.

I couldn't test everything though: feel free to use the sample project to see if other source of crashes could trigger a cookies loss.




回答2:


The problem seems to be that the cookies are cached and not saved out to a file immediately.

If you add a call to [storage _saveCookies] then it works - they are gone for good, even if you terminate the app straight afterwards. Of course, that method is private API, so it won't help you on the App Store. It would be good to find some way to trigger it!

I also found that the following CoreFoundation API works well - but unfortunately it is not exposed by Apple either:

extern CFTypeRef _CFHTTPCookieStorageGetDefault();
extern void CFHTTPCookieStorageDeleteAllCookies( CFTypeRef storage );
extern void CFHTTPCookieStorageSyncStorageNow( CFTypeRef storage );

...

CFTypeRef storage = _CFHTTPCookieStorageGetDefault();
CFHTTPCookieStorageDeleteAllCookies( storage );
CFHTTPCookieStorageSyncStorageNow( storage );



回答3:


I have found the following code to work.

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookieJar = [storage cookies];

for (NSHTTPCookie *cookie in cookieJar)
{
    [storage deleteCookie:cookie];
}


来源:https://stackoverflow.com/questions/5747012/nshttpcookies-refuse-to-be-deleted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!