将 cookie 添加到 Swift 中的 webview.load

Adding cookies to a webview.load in Swift

我尝试将网页添加到我的应用程序(有效),但是当我尝试添加 cookie 时出现此错误:"Cannot invoke 'load' with an argument list of type '(URLRequest, with: HTTPCookie?)'"

        let cookie1 = HTTPCookie(properties: [
        HTTPCookiePropertyKey.domain: "example.de",
        HTTPCookiePropertyKey.path: "/example/",
        HTTPCookiePropertyKey.secure: true,
        HTTPCookiePropertyKey.name: "PHPSESSID",
        HTTPCookiePropertyKey.value: "example"]) //this are the cookies I set 

    let example = URL(string:"example.de")
    let example2 = URLRequest(url: example!)
        webView.load(example2, with: cookie1) //here I tried to inject the cookie to the webviewload, 

我哪里做错了,有人知道我要改什么吗?

WKWebView 有两种加载方法,它们采用不同的参数

func load(Data, mimeType: String, characterEncodingName: String, baseURL: URL) -> WKNavigation?

Sets the webpage contents and base URL.

func loadFileURL(URL, allowingReadAccessTo: URL) -> WKNavigation?

Navigates to the requested file URL on the filesystem

它没有接受 cookies 参数的加载方法。这就是导致您错误的原因。

要真正修复它,您需要使用正确的方法通过 WKWebView 加载 cookie。有一些很好的例子here

万一 link 中断的预览:

let config = WKWebViewConfiguration()  
config.processPool = WKProcessPool()  
let cookies = HTTPCookieStorage.shared.cookies ?? [HTTPCookie]()  
cookies.forEach({ config.websiteDataStore.httpCookieStore.setCookie([=12=], completionHandler: nil) })  

let wkWebView = WKWebView(frame: bounds, configuration: config)