我极力尝试将自定义cookie添加到WKWebView
实例(不使用Javascript或类似的解决方法)。
在iOS 11及更高版本中,Apple提供了执行此操作的API:WKWebView
的{{1}}具有属性WKWebsiteDataStore
。
这是我的(示例)代码:
httpCookieStore
此后,如果我使用import UIKit
import WebKit
class ViewController: UIViewController {
var webView: WKWebView!
override func viewDidLoad() {
webView = WKWebView()
view.addSubview(webView)
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let cookie = HTTPCookie(properties: [
HTTPCookiePropertyKey.domain : "google.com",
HTTPCookiePropertyKey.path : "/",
HTTPCookiePropertyKey.secure : true,
HTTPCookiePropertyKey.name : "someCookieKey",
HTTPCookiePropertyKey.value : "someCookieValue"])!
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
cookieStore.setCookie(cookie) {
DispatchQueue.main.async {
self.webView.load(URLRequest(url: URL(string: "https://google.com")!))
}
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
webView.frame = view.bounds
}
}
,则会看到我的cookie在cookie列表中。
但是,当使用Safari的开发人员工具(当然使用iOS模拟器)检查Web视图时,cookie不会显示。
我还尝试使用HTTP代理(以我的情况为查尔斯)检查流量,以查看Cookie是否包含在我的HTTP请求中。不是。
我在这里做错了什么?如何将Cookie添加到webView.configuration.websiteDataStore.httpCookieStore.getAllCookies(completionHandler:)
(在iOS 11及更高版本上)?
答案 0 :(得分:3)
有点晚了,但是我想分享一个对我有用的解决方案,希望它也可以帮助在iOS 12上也面临同样问题的人。
这是我使用的简化工作流程:
为此,我创建了WKWebViewConfiguration的扩展:
extension WKWebViewConfiguration {
static func includeCookie(cookie:HTTPCookie, preferences:WKPreferences, completion: @escaping (WKWebViewConfiguration?) -> Void) {
let config = WKWebViewConfiguration()
config.preferences = preferences
let dataStore = WKWebsiteDataStore.nonPersistent()
DispatchQueue.main.async {
let waitGroup = DispatchGroup()
waitGroup.enter()
dataStore.httpCookieStore.setCookie(cookie) {
waitGroup.leave()
}
waitGroup.notify(queue: DispatchQueue.main) {
config.websiteDataStore = dataStore
completion(config)
}
}
}
在我的示例中,我使用它的方式如下:
override func viewDidLoad() {
self.AddWebView()
}
private func addWebView(){
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
preferences.javaScriptCanOpenWindowsAutomatically = true
let cookie = HTTPCookie(properties: [
.domain: COOKIE_DOMAIN,
.path: "/",
.name: COOKIE_NAME,
.value: myCookieValue,
.secure: "TRUE",
.expires: NSDate(timeIntervalSinceNow: 3600)
])
//Makes sure the cookie is set before instantiating the webview and initiating the request
if let myCookie = cookie {
WKWebViewConfiguration.includeCookie(cookie: myCookie, preferences: preferences, completion: {
[weak self] config in
if let `self` = self {
if let configuration = config {
self.webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width , height: self.view.frame.height), configuration: configuration)
self.view.addSubview(self.webView)
self.webView.load(self.customRequest)
}
}
}
}
答案 1 :(得分:0)
对google.com
的任何请求都会重定向到www.google.com
。
您需要将www.
添加到cookie的domain字段。如果域或路径与请求不匹配,则不会发送cookie。
您可以显式添加cookie。
let url = URL(string: "https://www.google.com")!
var request = URLRequest(url: url)
if let cookies = HTTPCookieStorage.shared.cookies(for: url) {
request.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookies)
}
self.webView.load(request)
答案 2 :(得分:0)
对于iOS 11或更高版本,您真的不需要担心cookie,因为它非常简单。像这样创建您的cookie。不要使其安全 true
let newcookie = HTTPCookie(properties: [
.domain: "domain",
.path: "/",
.name: "name",
.value: "vale",
.secure: "FALSE",
.expires: NSDate(timeIntervalSinceNow: 31556926)
])!
self.webview.configuration.websiteDataStore.httpCookieStore.setCookie(newcookie, completionHandler: {
// completion load your url request here. Better to add cookie in Request as well. like this way
request.addCookies()
//enable cookie through request
request.httpShouldHandleCookies = true
//load request in your webview.
})
请求范围在Cookie值“;”
之后添加extension URLRequest {
internal mutating func addCookies() {
var cookiesStr: String = ""
let mutableRequest = ((self as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
cookiesStr += cookie.name + "=" + cookie.value + ";"
mutableRequest.setValue(cookiesStr, forHTTPHeaderField: "Cookie")
self = mutableRequest as URLRequest
}
}
我还可以看到您没有设置wkwebview的WKWebViewConfiguration。设置您的wkwebview的配置。还要实现 WKHTTPCookieStoreObserver 并实现功能。
func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
// Must implement otherwise wkwebview cookie not sync properly
self.httpCookieStore.getAllCookies { (cookies) in
cookies.forEach({ (cookie) in
})
}
}
希望如此,这会起作用。