iOSは、WKWebViewで初めてCookieを携帯し、持続的にCookieを設定するスキームを設定し、親測定で利用可能

5354 ワード

プロジェクト内の複数の場所のWKWebViewはCookieキャッシュに影響し、テスト時に一つ一つ測定することを提案する。

  • 初回ログイン成功後のストレージCookie(ios 11システム以降と以前を区別する必要がある)
  • + (void)saveCookies:(WKWebView *)webView handle:(void (^)(BOOL isSuccessful))saveResponse {
        if (@available(iOS 11.0, *)) {
            WKHTTPCookieStore *shareCookie = webView.configuration.websiteDataStore.httpCookieStore;
            [shareCookie getAllCookies:^(NSArray * _Nonnull cookiesArray) {
                 [self dealSaveCookie:cookiesArray handle:saveResponse];
            }];
        } else {
            // Fallback on earlier versions
            NSHTTPCookieStorage * shareCookie = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            [self dealSaveCookie:[shareCookie cookies] handle:saveResponse];
        }
        
       
    }
    
    
    + (void)dealSaveCookie:(NSArray *)cookiesArray handle:(void (^)(BOOL isSuccessful))saveResponse {
        NSMutableArray *TempCookies = [NSMutableArray array];
        
        [TempCookies addObjectsFromArray:cookiesArray];
        NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:TempCookies];
        [[NSUserDefaults standardUserDefaults] setObject:cookiesData forKey:@"webCookie"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        if (saveResponse) {
            saveResponse(YES);
        }
    }
    
  • WKWebViewのrequestの前にCookie
  • を更新する
    + (NSArray *)updateCookies:(WKWebView *)webView {
        NSMutableArray *localCookies =[NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"webCookie"]];
    
        for (NSHTTPCookie *cookie in localCookies) {
            if (@available(iOS 11.0, *)) {
                WKHTTPCookieStore *cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
                [cookieStore setCookie:cookie completionHandler:nil];
            } else {
                NSHTTPCookieStorage * shareCookie = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                [shareCookie setCookie:cookie];
            }
        }
    
        return localCookies;
    }
    
  • WKWebViewの作成時に構成インスタンス
  • を追加する.
    - (WKWebView *)webView {
        if (!_webView) {
            _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:self.webConfig];
            [self.view addSubview:self.webView];
        }
        
        return _webView;
    }
    
    - (WKWebViewConfiguration *)webConfig {
        if (!_webConfig) {
            _webConfig = [[WKWebViewConfiguration alloc] init];
        }
        return _webConfig;
    }
    
  • は、要求時に次のように処理する(初回携帯Cookieを解決する)
  • .
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        self.webView.UIDelegate = self;
        self.webView.navigationDelegate = self;
         NSString *string = @"/oauth2/v2/authorize?access_type=offline&response_type=code&client_id=100253825&lang=zh-cn&redirect_uri=hms%3A%2F%2Fredirect_url&scope=https%3A%2F%2Fwww.huawei.com%2Fauth%2Faccount%2Fbase.profile+https%3A%2F%2Fsmarthome.com%2Fauth%2Fsmarthome%2Fskill+https%3A%2F%2Fsmarthome.com%2Fauth%2Fsmarthome%2Fdevices&state=state&display=mobile";
        NSArray *cookiesArray = [HWCookiesManager updateCookies:self.webView];
        
        NSString *string2 = [NSString stringWithFormat:@"https://login.vmall.com%@",string];
        
        //request Cookie
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:string2]];
        
        for (NSHTTPCookie *cookie in cookiesArray) {
            NSDictionary *cookieDict = [cookie dictionaryWithValuesForKeys:@[NSHTTPCookieName,
                                                                             NSHTTPCookieValue,
                                                                             NSHTTPCookieDomain,
                                                                             NSHTTPCookiePath]];
            NSString *cookieStr = @"";
            for (NSString *cookieKey in cookieDict.allKeys) {
                NSString *keyValue = [NSString stringWithFormat:@"%@=%@;",cookieKey,[cookieDict objectForKey:cookieKey]];
                cookieStr = [cookieStr stringByAppendingString:keyValue];
            }
            // cookie  request
            [request addValue:cookieStr forHTTPHeaderField:@"Cookie"];
        }
    
        //  Cookie 
        NSDictionary *cookieNewDict = [request allHTTPHeaderFields];
        NSString *cookieNewStr = [NSString stringWithFormat:@"document.cookie = '%@';", [cookieNewDict objectForKey:@"Cookie"]];
        WKUserContentController* userContentController = WKUserContentController.new;
        WKUserScript *cookieInScript = [[WKUserScript alloc] initWithSource:cookieNewStr
                                                                  injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                               forMainFrameOnly:NO];
        [userContentController addUserScript:cookieInScript];
        self.webView.configuration.userContentController = userContentController;
        
        //  Cookie
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [HWCookiesManager updateCookies:self.webView];
            [self.webView loadRequest:request];
        });
    }
    

    ソースアドレス:https://github.com/MacleChen/CFCookieWKWebView.git