最近在做一个项目,里面用到webview进行处理一些界面, 但是前提是需要在登录状态下.所以就处理一下方法
1. 在请求的时候进行cookie注入
// 在请求网站之前先把所有的cookie删除,然后注入需要的cookie
[self deleteCookie], [self setCookie];
[self.webView loadRequest:request];
2.在开始加载的时候进行cookie注入
//webView代理 开始加载
- (void)webViewDidStartLoad:(UIWebView*)webView{
NSLog(@"已经开始加载");
[self deleteCookie], [self setCookie];
}
设置cookie方法
//设置cookie
- (void)setCookie {
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"PHPSESSID" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"sessionID" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"www.baidu.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:30*24*60*60] forKey:NSHTTPCookieExpires];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
清除cookie方法
//清除cookie
- (void)deleteCookie{
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
// 获取到www.baidu.com下的cookies
NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString:@"www.baidu.com"]];
for (cookie in cookieAry) {
[cookieJar deleteCookie: cookie];
}
// 获取到所有的cookies
NSArray *cookieAry2 = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (cookie in cookieAry2) {
[cookieJar deleteCookie: cookie];
}
}
网友评论