iOS的Cookie存取看我絕對夠!!

si1ence發表於2017-12-14

2016.06.29

當前一些公司為了快速出一款app,很多時候採用UINavigationController+WebView或者NavigationController+UITabbarVC+WebView的方式,這樣就不可避免的需要使用cookie與Html5互動,下面講述幾種常用情景下cookie的新增方法:

一. UIWebView:

// 工廠類中儲存cookie的方法
+ (void)saveCookies {
    // 建立一個可變字典存放cookie
    NSMutableDictionary *fromappDict = [NSMutableDictionary dictionary];
    [fromappDict setObject:@"fromapp" forKey:NSHTTPCookieName];
    [fromappDict setObject:@"ios" forKey:NSHTTPCookieValue];
    // kDomain是公司app網址
    [fromappDict setObject:kDomain forKey:NSHTTPCookieDomain];
    [fromappDict setObject:kDomain forKey:NSHTTPCookieOriginURL];
    [fromappDict setObject:@"/" forKey:NSHTTPCookiePath];
    [fromappDict setObject:@"0" forKey:NSHTTPCookieVersion];

    // 將可變字典轉化為cookie
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:fromappDict];

    // 獲取cookieStorage
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]
 
    // 儲存cookie
    [cookieStorage setCookie:cookie];
}
複製程式碼
  • UIWebView使用時間較長,只要在cookieStorage中設定了相應的cookie,每次就會自動帶上;
  • 但是這樣的弊端是隨著與H5的互動增加,Cookie佔用的空間越來越大,每次互動都夾帶大量的cookie,不僅增加伺服器端壓力,也浪費使用者的流量。比如每次互動都夾帶5kb的cookie內容,但是真正用到的只有兩三百位元組。

二. WKWebView

  • WKWebView相比於UIWebView:

    • 速度快了一倍,記憶體卻減少為原來的一半;
    • cookie不再是自動攜帶,需要手動設定;
    • 互動更加順暢,比如app底部四個tabBar也都是網頁的,在UIWebView下點選,整個H5頁面都會閃白一下,但是在WKWebView下點選,四個tabBar效果與原生app效果更加類似,不會有閃白現象。
    • 增減了一些代理方法,更方便的進行協議攔截和進度條展示
  • 1.在建立的時候存放到WKUserScript中進行新增cookie

    WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
    // 設定偏好設定
    webConfig.preferences = [[WKPreferences alloc] init];
    // 預設為0
    webConfig.preferences.minimumFontSize = 10;
    // 預設認為YES
    webConfig.preferences.javaScriptEnabled = YES;
    // 在iOS上預設為NO,表示不能自動通過視窗開啟
    webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;

    // web內容處理池
    webConfig.processPool = [[WKProcessPool alloc] init];
    // 將所有cookie以document.cookie = 'key=value';形式進行拼接
    #warning 然而這裡的單引號一定要注意是英文的,不要問我為什麼告訴你這個(手動微笑)
    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.載入某個url的時候新增cookie

如果WKWebView在載入url的時候需要新增cookie,需要先手動獲取當前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重複,先放到字典進行去重,再進行拼接
    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];
    
    // 建立可變字典用於存放Cookie
    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
    
    // 存放新新增的cookie
    #warning 單個的Cookie還好,但是樓主在工廠類方法中拼接了一個包含6個裝置資訊的value值,最後忘記加分號了,測試也沒測出來
    #warning 因為不影響功能,但是後面的cookie就自動拼接上了,H5那邊也識別不到,險造成重大事故(涉及金融。。),望後來者看到,提前做好準備(就憑這個坑,你得給我個贊)
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@"fromapp=ios;"];

    // 獲取
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
    }
    
    // cookie重複,先放到字典去重,再進行拼接
    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];
    
    // 設定引數字典
    NSDictionary *paraDict = @{
                                  @"key" : value
                                  };
    // 傳送請求,處理結果
    [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);
    }];
複製程式碼

相關文章