我正在开发一个应用程序,服务器向我发送一个 cookie 来识别用户。
我的连续请求需要该 cookie 才能获得用户期望的响应。我无法理解的是 NSHTTPCookieStorage 的共享实例如何以及何时丢失其 cookie。
我使用的第一个解决方案是在应用程序终止时将 cookie 从我的服务器存档并保存到用户默认值,然后在应用程序启动时从我的服务器中清除现有的 cookie 并重置我存储的那些。在开发过程中我没有遇到问题,因为调试会话非常短,通常不需要将应用程序置于后台。
在 beta 测试期间,麻烦开始了。我带来的技巧是不仅在应用程序终止时保存 cookie,而且在将这些 cookie 交还给我的 API 调用之后保存。并且不仅在应用程序启动时加载保存的 cookie,而且在应用程序返回前台时加载。
NSHTTPCookieStorage 共享实例如何摆脱这些 cookie 以及处理它的最佳实践是什么,因为它是我的应用程序的重要组成部分,如果没有更有经验的开发人员支持,我不能相信这样一个被黑的解决方案。
预先感谢您的回答
编辑:以下是保存/读取/清除 cookie 的方法
-(void)saveStoredCookies
{
NSURL *httpUrl = @"http://myServer.com";
NSURL *httpsUrl = @"https://myServer.com";
NSArray *httpCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpUrl];
NSData *httpCookiesData = [NSKeyedArchiver archivedDataWithRootObject:httpCookies];
[[NSUserDefaults standardUserDefaults] setObject:httpCookiesData forKey:@"savedHttpCookies"];
NSArray *httpsCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpsUrl];
NSData *httpsCookiesData = [NSKeyedArchiver archivedDataWithRootObject:httpsCookies];
[[NSUserDefaults standardUserDefaults] setObject:httpsCookiesData forKey:@"savedHttpsCookies"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)readStoredCookies
{
//clear, read and install stored cookies
NSURL *httpUrl = @"http://myServer.com";
NSURL *httpsUrl = @"https://myServer.com";
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpUrl];
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpsUrl];
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
NSData *httpCookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedHttpCookies"];
if([httpCookiesData length]) {
NSArray *savedCookies = [NSKeyedUnarchiver unarchiveObjectWithData:httpCookiesData];
for (NSHTTPCookie *cookie in savedCookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
NSData *httpsCookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedHttpsCookies"];
if([httpsCookiesData length]) {
NSArray *savedCookies = [NSKeyedUnarchiver unarchiveObjectWithData:httpsCookiesData];
for (NSHTTPCookie *cookie in savedCookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
}
-(void)clearStoredCookies
{
NSURL *httpUrl = @"http://myServer.com";
NSURL *httpsUrl = @"https://myServer.com";
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpUrl];
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpsUrl];
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}