Swift3.0 设置WKWebView cookies

      // 设置访问的URL

        let url = NSURL(string: "http://xxxxxxxx")
        
        // 根据URL创建请求
        let request = NSURLRequest(url: url as! URL)
    
        //获取cookies并放入请求头部
        let userContentController = WKUserContentController()
        if let cookies = HTTPCookieStorage.shared.cookies{
            print(cookies)
            let script = getJSCookiesString(cookies: cookies)
            let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
            userContentController.addUserScript(cookieScript)
        }
        let webviewConfig = WKWebViewConfiguration()
        webviewConfig.userContentController = userContentController
        
        // 创建WKWebView
        let webView = WKWebView(frame: UIScreen.main.bounds ,configuration: webviewConfig)

        // WKWebView加载请求
        webView.load(request as URLRequest)
        
        // 将WKWebView添加到视图

        view.addSubview(webView)



//Generates script to create given cookies   

public func getJSCookiesString(cookies: [HTTPCookie]) -> String {
        var result = ""
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
        dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
        
        for cookie in cookies {
            result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
            if let date = cookie.expiresDate {
                result += "expires=\(dateFormatter.string(from: date)); "
            }
            if (cookie.isSecure) {
                result += "secure; "
            }
            result += "'; "
        }
        return result
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值