在網(wǎng)絡(luò)請(qǐng)求中,有一部分需要添加cookie骄噪,接下來就把為web添加cookie的方法小小列舉一下莽鸿,其實(shí)所有的要添加cookie的網(wǎng)絡(luò)請(qǐng)求包括web山憨,最終都是要在request上添加焦蘑,如下:
if(_webView == nil) {
? ? ? ? // 1)創(chuàng)建WebView_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,0, Kwidth, Kheight-64)];
? ? ? ? // 2)設(shè)置代理_webView.delegate= self;
? ? ? ? _webView.scalesPageToFit = YES;
? ? ? ? _webView.scrollView.bounces = NO;
? ? }
? ? // 3)設(shè)置URL地址NSURL *url = [NSURL URLWithString:strUrl];
? ? NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
? ? NSDictionary *cookie = [AppInfo shareAppInfo].userModel.cookies;
? ? if(cookie != nil) {
? ? ? ? [request addValue:[self readCurrentCookieWith:cookie] forHTTPHeaderField:@"Cookie"];
? ? }else{
? ? ? ? [request addValue:@""forHTTPHeaderField:@"Cookie"];
? ? }
? ? [_webView loadRequest:request];
? ? [self.view addSubview:_webView];
其中獲得cookie的信息我封裝了一下:
#pragmamark - 拼接cookie- (NSString*)readCurrentCookieWith:(NSDictionary*)dic{
? ? if(dic == nil) {
? ? ? ? return nil;
? ? }else{
? ? ? ? NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
? ? ? ? NSMutableString *cookieString = [[NSMutableString alloc] init];
? ? ? ? for(NSHTTPCookie*cookiein [cookieJar cookies]) {
? ? ? ? ? ? [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value];
? ? ? ? }
? ? ? ? //刪除最后一個(gè)“;”[cookieString deleteCharactersInRange:NSMakeRange(cookieString.length -1,1)];
? ? ? ? return cookieString;
? ? }
}?
[self setCookie];//設(shè)置cookie
在此之前盒发,設(shè)置cookie例嘱。
//設(shè)置cookie?
- (void)setCookie{ NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];? [cookiePropertiessetObject:@"cookie_user"forKey:NSHTTPCookieName];? [cookiePropertiessetObject:uidforKey:NSHTTPCookieValue];? [cookiePropertiessetObject:@"xxx.xxx.com"forKey:NSHTTPCookieDomain];[cookiePropertiessetObject:@"/"forKey:NSHTTPCookiePath];? [cookiePropertiessetObject:@"0"forKey:NSHTTPCookieVersion]; [cookiePropertiessetObject:[[NSDate date] dateByAddingTimeInterval:2629743]forKey:NSHTTPCookieExpires];? NSHTTPCookie *cookieuser = [NSHTTPCookie cookieProperties];? [[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookie:cookieuser];?
}
NSHTTPCookieStorage實(shí)現(xiàn)管理共享的cookie存儲(chǔ)一個(gè)singleton對(duì)象(共享實(shí)例)。 這些cookies是所有的應(yīng)用程序之間的共享和跨進(jìn)程同步保存
//清除cookie?
- (void)deleteCookie{NSHTTPCookie *cookie;NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString: _urlstr]];for (cookiein cookieAry) {?
? ? ? ? [cookieJar deleteCookie: cookie];?
? ? }?
}
附上原博主鏈接原文