這兩天有個項目需求年栓,在網(wǎng)上找了好多博文都不可以拿來就能實現(xiàn)(對于伸手黨怎么能行),為了避免浪費大家的時間我在這里給出一份一定可行的方法:
1薄霜、相關(guān)知識點介紹
- iOS在
UIWebView
中獲取的cookie的方法:NSHTTPCookieStorage * nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage]
- 再具體獲取某個域的餅干:
NSArray* cookiesURL = [nCookies cookiesForURL:[NSURL URLWithString:@“你的URL”]];
- 通過
[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie]
方法將cookies
來保存起來某抓,但是這樣雖然可以保存cookies
但是你應(yīng)用退出之后還是會丟失(其實是cookies過期的問題),做好的方法是把cookies
放到NSUserDefaults
保存起來:
2惰瓜、實現(xiàn)方法
- 簡單粗暴直接上碼:GitHub Demo歡迎star, 你的star就是對我最好的鼓勵.
1.在UIWebView的代理方法中實現(xiàn)獲取cookies
并將cookies
放到NSUserDefaults保存起來:(void)webViewDidFinishLoad:(UIWebView *)webView
中寫入
需要注意的是你的CookieName
否副,
NSArray *nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSHTTPCookie *cookie;
for (id c in nCookies)
{
if ([c isKindOfClass:[NSHTTPCookie class]])
{
cookie=(NSHTTPCookie *)c;
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
崎坊,并設(shè)置cookies
备禀,
NSArray *cookies =[[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"];
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[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 = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
注意:要在[self.webView loadRequest:req];之前設(shè)置獲取cookies!
到現(xiàn)在為止你的應(yīng)用肯定就已經(jīng)實現(xiàn)了你想要的功能!
感謝樓下@440bd488f596這位同學(xué)提供的新方案痹届,供大家參考:
NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:
[NSDictionary dictionaryWithObject:
[[NSString alloc] initWithFormat:@"token=%@;",self.token]
forKey:@"Set-Cookie"]
forURL:url];
(其中連接上面實現(xiàn)的稍微有些問題呻待,我在我這里已經(jīng)進行了修改)功能實現(xiàn)參考鏈接
----By ZPengs