在使用UIWebView加载网页时,有时会需要传Cookie
实现代码如下:
[self setCookie];//设置cookie
在此之前,设置或者删除cookie。
NSURL *url = [NSURL URLWithString:_urlstr];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
[self.myWeb loadRequest:request];
//////////////////////////////////////////////////////
//设置cookie
- (void)setCookie{
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"cookie_user" forKey:NSHTTPCookieName];
[cookieProperties setObject:uid forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"xxx.xxx.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];
NSHTTPCookie *cookieuser = [NSHTTPCookie cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
}
NSHTTPCookieStorage
实现管理共享的cookie存储一个singleton对象(共享实例)。 这些cookies是所有的应用程序之间的共享和跨进程同步保存
//清除cookie
- (void)deleteCookie{
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString: _urlstr]];
for (cookie in cookieAry) {
[cookieJar deleteCookie: cookie];
}
}