WKWebView 手动添加和清除Cookie

原文链接

在原生登录的成功回调里执行[NSKeyedArchiver archiveRootObject:[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] toFile:kUserCookieFile];保存登录获取的Cookie

添加Cookie

在设置WKWebview request前调用:

 NSString* value1;
    NSString* value2;
    for (NSHTTPCookie *cookie in [NSKeyedUnarchiver unarchiveObjectWithFile:kUserCookieFile])
    {
        if ([cookie.name isEqualToString:@"key1"])
        {
            value1 = cookie.value;
        }
        else if ([cookie.name isEqualToString:@"key2"])
        {
            value2 = cookie.value;
        }
    [request setValue:[NSString stringWithFormat:@"key1=%@;key2=%@;",value1,value2] forHTTPHeaderField:@"Cookie"];

如果发送AJAX请求的话,在初始化WKWebview的地方:

WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc] 
    initWithSource: @"document.cookie = 'TeskCookieKey1=TeskCookieValue1';document.cookie = 'TeskCookieKey2=TeskCookieValue2';"
    injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
// again, use stringWithFormat: in the above line to inject your values programmatically
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
webViewConfig.userContentController = userContentController;
WKWebView * webView = [[WKWebView alloc] initWithFrame:CGRectMake(/*set your values*/) configuration:webViewConfig];

清除Cookie

比如在登出的时候需要清除Cookie,使用WKWebview的话就需要使用如下的方法:

  if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0)
    {
        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];

        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes
                                                   modifiedSince:dateFrom
                                               completionHandler:^{

                                                   // Done

                                               }];
    }
    [[NSFileManager defaultManager] removeItemAtPath:kUserInfoFile error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:kUserTokenFile error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:kUserCookieFile error:nil];
    [webView.configuration.userContentController removeAllUserScripts];

你可能感兴趣的:(WKWebView 手动添加和清除Cookie)