// 设置访问的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
}