Swift 为WKWebView设置cookie

2019-06-13  本文已影响0人  独孤伊人_xie

登录页面为原生,为了将access_token传给web页面,通过给设置web页面cookie的方式,传access_token
第一种

let cookieValue = "document.cookie = 'refresh_token=true';document.cookie = 'access_token=appstore';"
let cookieScript = WKUserScript.init(source: cookieValue, injectionTime: .atDocumentStart, forMainFrameOnly: false)
let userContent = WKUserContentController.init()
userContent.addUserScript(cookieScript)
config.userContentController = userContent
let webView = WKWebView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WHIDTH(), height: SCREEN_HEIGHT()), configuration: config)

第二种

let url:NSURL = NSURL.init(string: "")!
var host = url.host
let cookie = HTTPCookie(properties: [
            HTTPCookiePropertyKey.domain : host!,
            HTTPCookiePropertyKey.originURL: host!,
            HTTPCookiePropertyKey.path : "/",
            HTTPCookiePropertyKey.secure : true,
            HTTPCookiePropertyKey.name : "info",
            HTTPCookiePropertyKey.value :  "value"])!
        if #available(iOS 11.0, *) {
            let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
            cookieStore.setCookie(cookie) {
            }
        } else {
            HTTPCookieStorage.shared.setCookie(cookie)
        }

第三种

var urlRequest:NSMutableURLRequest = NSMutableURLRequest.init(url: url as URL)
urlRequest.setValue("info=value", forHTTPHeaderField: "Cookie")
webView.load((urlRequest) as URLRequest)
上一篇 下一篇

猜你喜欢

热点阅读