美文网首页爱编程
iOS开发-WKWebView设置cookie

iOS开发-WKWebView设置cookie

作者: 来者可追文过饰非 | 来源:发表于2018-08-31 16:28 被阅读2118次

    1.初始化WKWebView时设置cookie

    #pragma mark - lazy
    
    - (WKWebView *)webView {
        if (!_webView) {
            WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
            // 偏好设置
            config.preferences = [[WKPreferences alloc] init];
            config.preferences.minimumFontSize = 10;
            config.preferences.javaScriptEnabled = YES;
            config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
            
            // 设置cookie
            config.processPool = [[WKProcessPool alloc] init];
            NSDictionary *dic = '你的cookie数据';
            // 将所有cookie以document.cookie = 'key=value';形式进行拼接
            NSMutableString *cookie = @"".mutableCopy;
            
            if (dic) {
                for (NSString *key in dic.allKeys) {
                    [cookie appendFormat:@"document.cookie = '%@=%@';\n",key,dic[key]];
                }
            }
            
            WKUserContentController *userContentController = [[WKUserContentController alloc] init];
            WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
            [userContentController addUserScript:cookieScript];
            
            config.userContentController = userContentController;
            config.selectionGranularity = WKSelectionGranularityDynamic;
            config.allowsInlineMediaPlayback = YES;
            config.mediaPlaybackRequiresUserAction = false;
            
            CGRect frame = 'webview的frame';
            _webView = [[WKWebView alloc] initWithFrame:frame configuration:config];
        }
        return _webView;
    }
    

    2.WKWebView已经存在时,设置cookie

    - (void)setcookie {
        
        if (!_webView) {
            return;
        }
        NSDictionary *dic = '你的cookie数据';
        NSSLog(@"%@",dic);
        // 将所有cookie以document.cookie = 'key=value';形式进行拼接
        NSMutableString *cookie = @"".mutableCopy;
        for (NSString *key in dic.allKeys) {
            [cookie appendFormat:@"document.cookie = '%@=%@';\n",key,dic[key]];
        }
        self.cookie = cookie.copy;
        NSString *cookieValue = cookie;
        [_webView evaluateJavaScript:cookieValue completionHandler:^(id result, NSError *error) {
            NSSLog(@"cookie-------%@",result);
        }];
    }
    

    相关文章

      网友评论

        本文标题:iOS开发-WKWebView设置cookie

        本文链接:https://www.haomeiwen.com/subject/wsxewftx.html