說下cookie,cookie在webView需要登錄的時候,webView會根據(jù)這個cookie胀茵,自動登錄:
NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//獲取cookie
for (NSHTTPCookie * cookie in array) { //遍歷cookie
[cookie name]//輸出所有cookie的key
[cookie value]//輸出所有cookie的value
}
由于我這是從后臺獲得的cookie吐句,要想當(dāng)遇到網(wǎng)頁的時候胁后,讓網(wǎng)頁自動讀取cookie,我要先把它加入cookie中
把從后臺獲取的cookie加入到系統(tǒng)的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登錄的那個網(wǎng)址
[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择同,其中就有加進(jìn)去的那對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