Adding cookies to a webview.load in Swift

1k Views Asked by At

I tried to add a Webpage to my App(that works) but when I try to add cookies it gave me this error : "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, 

What I did wrong, do anybody knew what I have to change?

1

There are 1 best solutions below

0
On BEST ANSWER

WKWebView has two load methods which take different params

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

It does not have a load method which accepts a cookies parameter. This is what causes your error.

To actually fix it you need to use the proper ways of loading cookies with WKWebView. There are some good examples here

A preview in case that link breaks:

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

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