说下cookie,cookie在webView需要登录的时候,webView会根据这个cookie,自动登录:
NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
for (NSHTTPCookie * cookie in array) { //遍历cookie
[cookie name]//输出所有cookie的key
[cookie value]//输出所有cookie的value
}
由于我这是从后台获得的cookie,要想当遇到网页的时候,让网页自动读取cookie,我要先把它加入cookie中
把从后台获取的cookie加入到系统的cookie队列:
由于后台传过来的是一个字典,{cookieName:name,cookiePasswd:passed}
NSMutableDictionary * cookiePreperties = [NSMutableDictionary dictionary];
[cookiePreperties setObject:@"cookieName" forKey:NSHTTPCookieName];
[cookiePreperties setObject:name forKey:NSHTTPCookieValue];
[cookiePreperties setObject:@"http://" forKey:NSHTTPCookieDomain];//http后面跟需要cookie登录的那个网址
[cookiePreperties setObject:@"http://" forKey:NSHTTPCookieOriginURL];
[cookiePreperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookiePreperties setObject:@"0" forKey:NSHTTPCookieVersion];
NSHTTPCookie * cookie = [NSHTTPCookie cookieWithProperties:cookiePreperties];
NSMutableDictionary * cookiePrepertiess = [NSMutableDictionary dictionary];
[cookiePrepertiess setObject:@"cookiePasswd" forKey:NSHTTPCookieName];
[cookiePrepertiess setObject:passwd forKey:NSHTTPCookieValue];
[cookiePrepertiess setObject:@"http://" forKey:NSHTTPCookieDomain];
[cookiePrepertiess setObject:@"http://" forKey:NSHTTPCookieOriginURL];
[cookiePrepertiess setObject:@"/" forKey:NSHTTPCookiePath];
[cookiePrepertiess setObject:@"0" forKey:NSHTTPCookieVersion];
NSHTTPCookie * cookies = [NSHTTPCookie cookieWithProperties:cookiePrepertiess];
[[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookie:cookie];
[[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookie:cookies];
然后在输出cookie,其中就有加进去的那对cookie;
添加了cookie就有读取cookie:
NSString *userstring;
NSString * passString;
NSMutableArray * cookArray = [[NSMutableArray alloc]init];
NSArray * array = [[NSHTTPCookieStoragesharedHTTPCookieStorage]cookies];
//输出cookie
for (NSHTTPCookie * cookie in array) {
[cookArray addObject:[cookie name]];
if ([[cookie name] isEqualToString:@"cookieName"]) {
userstring = [cookie value];
}if ([[cookie name] isEqualToString:@"cookiePasswd"]) {
passString = [cookie value];
}
}
//添加cookie,用户名
NSArray * heardCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:[NSDictionary
dictionaryWithObject:[[NSString alloc]
initWithFormat:@"cookieName=%@", userstring] //这里的cookieName要后台给
forKey:@"Set-Cookie"]
forURL:[NSURL URLWithString:@"http://"]];
[[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookies:heardCookie forURL:[NSURL URLWithString:@"http://"] mainDocumentURL:nil];
//passwd
NSArray * heardCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:[NSDictionary
dictionaryWithObject:[[NSString alloc]
initWithFormat:@"cookiePasswd =%@", passString] //cookiePasswd也是后台给
forKey:@"Set-Cookie"]
forURL:[NSURL URLWithString:@"http://"]];
[[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookies:heardCookie forURL:[NSURL URLWithString:@"http://"] mainDocumentURL:nil];
end