1、相關介紹
iOS在UIWebView中獲取的cookie的方法:NSHTTPCookieStorage * nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
再具體獲取某個域的cookie:NSArray* cookiesURL = [nCookies cookiesForURL:[NSURL URLWithString:@"你的URL"]];
通過[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:userCookie]方法將 cookies來保存起來,但是這樣雖然可以保存cookies但是你應用退出之後還是會丟失(其實是cookies過期的問題),做好的方法是把cookies放到NSUserDefaults保存起來.
2、實現
1.在UIWebView的代理方法中實現獲取cookies並將cookies放到NSUserDefaults保存起來:- (void)webViewDidFinishLoad:(UIWebView*)webView中寫入
- (void)webViewDidFinishLoad:(UIWebView*)webView{ NSArray *nCookies = [[NSHTTPCookieStoragesharedHTTPCookieStorage] cookies]; for (NSHTTPCookie *cookie in nCookies){ if ([cookie isKindOfClass:[NSHTTPCookie class]]){ if ([cookie.name isEqualToString:@"PHPSESSID"]) { NSNumber *sessionOnly =[NSNumber numberWithBool:cookie.sessionOnly]; NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure]; NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil]; [[NSUserDefaults standardUserDefaults] setObject:cookies forKey:@"cookies"]; break; } } } }
2.獲取cookies:運行之後,UIWebView加載url之前獲取保存好的cookies,並設置cookies,
NSArray *cookies =[[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"]; if (cookies.count >0) { NSMutableDictionary *cookieProperties = [NSMutableDictionarydictionary]; [cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName]; [cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue]; [cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain]; [cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath]; NSHTTPCookie *cookieuser = [NSHTTPCookiecookieWithProperties:cookieProperties]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser]; }
注意:要在[self.webView loadRequest:req];之前設置獲取cookies!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。