當(dāng)前一些公司為了快速出一款app,很多時(shí)候采用UINavigationController+WebView或者NavigationController+UITabbarVC+WebView的方式赘被,這樣就不可避免的需要使用cookie與Html5交互是整,下面講述幾種常用情景下cookie的添加方法:
一. UIWebView:
// 工廠類中存儲cookie的方法
+ (void)saveCookies {
// 創(chuàng)建一個(gè)可變字典存放cookie
NSMutableDictionary *fromappDict = [NSMutableDictionary dictionary];
[fromappDict setObject:@"fromapp" forKey:NSHTTPCookieName];
[fromappDict setObject:@"ios" forKey:NSHTTPCookieValue];
// kDomain是公司app網(wǎng)址
[fromappDict setObject:kDomain forKey:NSHTTPCookieDomain];
[fromappDict setObject:kDomain forKey:NSHTTPCookieOriginURL];
[fromappDict setObject:@"/" forKey:NSHTTPCookiePath];
[fromappDict setObject:@"0" forKey:NSHTTPCookieVersion];
// 將可變字典轉(zhuǎn)化為cookie
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:fromappDict];
// 獲取cookieStorage
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]
// 存儲cookie
[cookieStorage setCookie:cookie];
}
- UIWebView使用時(shí)間較長,只要在cookieStorage中設(shè)置了相應(yīng)的cookie帘腹,每次就會自動帶上贰盗;
- 但是這樣的弊端是隨著與H5的交互增加,Cookie占用的空間越來越大阳欲,每次交互都夾帶大量的cookie舵盈,不僅增加服務(wù)器端壓力,也浪費(fèi)用戶的流量球化。比如每次交互都夾帶5kb的cookie內(nèi)容秽晚,但是真正用到的只有兩三百字節(jié)。
二. WKWebView
-
WKWebView相比于UIWebView:
- 速度快了一倍筒愚,內(nèi)存卻減少為原來的一半赴蝇;
- cookie不再是自動攜帶,需要手動設(shè)置巢掺;
- 交互更加順暢句伶,比如app底部四個(gè)tabBar也都是網(wǎng)頁的,在UIWebView下點(diǎn)擊陆淀,整個(gè)H5頁面都會閃白一下考余,但是在WKWebView下點(diǎn)擊,四個(gè)tabBar效果與原生app效果更加類似轧苫,不會有閃白現(xiàn)象楚堤。
- 增減了一些代理方法,更方便的進(jìn)行協(xié)議攔截和進(jìn)度條展示
1.在創(chuàng)建的時(shí)候存放到WKUserScript中進(jìn)行添加cookie
WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
// 設(shè)置偏好設(shè)置
webConfig.preferences = [[WKPreferences alloc] init];
// 默認(rèn)為0
webConfig.preferences.minimumFontSize = 10;
// 默認(rèn)認(rèn)為YES
webConfig.preferences.javaScriptEnabled = YES;
// 在iOS上默認(rèn)為NO,表示不能自動通過窗口打開
webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;
// web內(nèi)容處理池
webConfig.processPool = [[WKProcessPool alloc] init];
// 將所有cookie以document.cookie = 'key=value';形式進(jìn)行拼接
#warning 然而這里的單引號一定要注意是英文的身冬,不要問我為什么告訴你這個(gè)(手動微笑)
NSString *cookieValue = @"document.cookie = 'fromapp=ios';document.cookie = 'channel=appstore';";
// 加cookie給h5識別衅胀,表明在ios端打開該地址
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: cookieValue
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
webConfig.userContentController = userContentController;
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:frame configuration:webConfig];
wkWebView.UIDelegate = wkWebView;
wkWebView.navigationDelegate = wkWebView;
- 2.加載某個(gè)url的時(shí)候添加cookie
如果WKWebView在加載url的時(shí)候需要添加cookie,需要先手動獲取當(dāng)前NSHTTPCookieStorage中的所有cookie酥筝,然后將cookie放到NSMutableURLRequest請求頭中
- (void)loadRequestWithUrlString:(NSString *)urlString {
// 在此處獲取返回的cookie
NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
[cookieDic setObject:cookie.value forKey:cookie.name];
}
// cookie重復(fù)滚躯,先放到字典進(jìn)行去重,再進(jìn)行拼接
for (NSString *key in cookieDic) {
NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
[cookieValue appendString:appendString];
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
[self loadRequest:request];
}
3.AFNetworking
AFNetworking存取cookie就比較常見了樱哼,話不多說哀九,都在代碼里了
// 獲取AFHTTPRequestOperationManager
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
// 創(chuàng)建可變字典用于存放Cookie
NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
// 存放新添加的cookie
#warning 單個(gè)的Cookie還好剿配,但是樓主在工廠類方法中拼接了一個(gè)包含6個(gè)設(shè)備信息的value值搅幅,最后忘記加分號了,測試也沒測出來
#warning 因?yàn)椴挥绊懝δ芎襞撸呛竺娴腸ookie就自動拼接上了茄唐,H5那邊也識別不到,險(xiǎn)造成重大事故(涉及金融蝇更。沪编。),望后來者看到年扩,提前做好準(zhǔn)備(就憑這個(gè)坑蚁廓,你得給我個(gè)贊)
NSMutableString *cookieValue = [NSMutableString stringWithFormat:@"fromapp=ios;"];
// 獲取
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
[cookieDic setObject:cookie.value forKey:cookie.name];
}
// cookie重復(fù),先放到字典去重厨幻,再進(jìn)行拼接
for (NSString *key in cookieDic) {
NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
[cookieValue appendString:appendString];
}
// 將cookie存到請求頭中
[operationManager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
// 拼接url地址
NSString *urlStr = [NSString stringWithFormat:@"%@%@", kHostIP, kPath];
// 設(shè)置參數(shù)字典
NSDictionary *paraDict = @{
@"key" : value
};
// 發(fā)送請求相嵌,處理結(jié)果
[operationManager POST:urlStr parameters:paraDict success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"responseObject-->%@", responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"error-->%@", error);
}];