iOS - web view cookies not set

2019-07-29 17:24发布

问题:

I am trying to set cookies in my iOS like this:

    let url = URL(string: "url")!
    let jar = HTTPCookieStorage.shared
    let cookieHeaderField = ["Set-Cookie": "key1=value1, key2=value2"]
    let cookies = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url)
    jar.setCookies(cookies, for: url, mainDocumentURL: url)

    let request = URLRequest(url: url)

    viewerWebKit.load(request)

Then I am printing them like this:

    viewerWebKit.configuration.websiteDataStore.httpCookieStore.getAllCookies( { (cookies) in
        cookies.forEach({ (cookie) in
            print(cookie.name)
        })
    })

All cookies are printed and they seem to be set normally. But when I use the Web inspector of my safari to see, if they are really set then nothing is there. No cookies are set. What is the problem? Do I need to accept them? Is safari blocking them? How can I set them normally, to be visible in web inspector?

I also tried this approach:

import UIKit
import WebKit

class ViewWrapper: UIViewController, WKNavigationDelegate {

var loginToken: String?
@IBOutlet weak var viewerWebKit: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    var urlRequest = URLRequest(url: URL(string: "url")!)
    urlRequest.httpShouldHandleCookies = true

    let newcookie = HTTPCookie(properties: [
        .domain: "domain",
        .path: "",
        .name: "key",
        .value: "value",
        .secure: "FALSE",
        .expires: NSDate(timeIntervalSinceNow: 31556926)
        ])

    viewerWebKit.configuration.websiteDataStore.httpCookieStore.setCookie(newcookie!, completionHandler: {
        self.viewerWebKit.load(urlRequest)
    })

    viewerWebKit.configuration.websiteDataStore.httpCookieStore.getAllCookies( { (cookies) in
        cookies.forEach({ (cookie) in
            print(cookie.name)
        })
    })

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func loadView() {
    viewerWebKit = WKWebView()
    viewerWebKit.navigationDelegate = self
    view = viewerWebKit
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    title = webView.title
}

func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
    cookieStore.getAllCookies({ (cookies) in
        cookies.forEach({ (cookie) in
            print(cookie.name)
        })
    })
}

}

but it didn't work too.

This is what I see in safari debug console:

Cookies are not set.

This is what I see in Xcode's console.

So here it seems to be set. But it is not in reality. Printing code prints cookies. But they are not all visible in safari console. How is that possible? Cookies csrftoken and sessionid are set by website, not by my app. And they are visible in both printing and debug console.

回答1:

Set cookie through this. also after request create set

urlRequest.httpShouldHandleCookies = true


self.configuration.websiteDataStore.httpCookieStore.setCookie("your_http_cookie", completionHandler: {

//do whatever you want. i suggest after cookie set load your webview.

 })

Implement this observers WKHTTPCookieStoreObserver in your class.

WKWebsiteDataStore.default().httpCookieStore.add(self)
 func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
    // Must implement otherwise wkwebview cookie not sync properly
    self.httpCookieStore.getAllCookies { (cookies) in
        cookies.forEach({ (cookie) in
           // print your cookie here
        })
    }
}