ios app退出後cookies丟失的解決方法
阿新 • • 發佈:2019-02-05
前兩天我在做uiwebview通過cookies自動登入的時候,發現app退出後cookies丟失,搞了一天找不出原因,最後發現ios的cookies需要程式設計師手動設定儲存時間,預設下,cookies的儲存時間是app退出後cookie就會被清掉!
怎麼儲存呢?簡單得讓人哭笑不得!在app進入後臺的時候指向下面程式碼(不喜歡在delegate中執行,那就通過接受進入後臺的通知):
NSHTTPCookie *cookie;NSHTTPCookieStorage *nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookiesURL = [nCookies cookiesForURL:[NSURL URLWithString:youURL
for (id c in cookiesURL)
{
if ([c isKindOfClass:[NSHTTPCookie class]])
{
cookie=(NSHTTPCookie *)c;
if ([cookie.name isEqualToString:@"PHPSESSID"]) {//我的cookies的名字是 "PHPSESSID",你在上一行打個斷點看看你的cookies的name是什麼
NSDate *expiresDate = [NSDate dateWithTimeIntervalSinceNow:3600*24*30*12];//當前點後,儲存一年左右
NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, expiresDate, cookie.domain, cookie.path, nil];
if(cookies){
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName];
[cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue];
[cookieProperties setObject:[cookies objectAtIndex:2] forKey:NSHTTPCookieExpires];
[cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain];
[cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath];
NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
}
break;
}
}
} 也就是說,每次退出都會講儲存時間更新為一年,所以不用擔心cookies過期問題!
陸陸續續有人加qq提問,基本上都是這個問題:基本都是在[webView loadRequest:登入url],這是錯的,應該load主頁的url,沒用儲存cookies的話會自動轉跳到登入url的,如果load的是登入url,那設定了cookie也沒用!!!
好了現在試試是不是可以自動更新了!