乐闻世界logo
搜索文章和话题

Can I set the cookies to be used by a WKWebView?

1个答案

1

You can set the cookies used by WKWebView.

In iOS, WKWebView is provided by the WebKit framework for loading and displaying web content. There are several main ways to set cookies:

1. Setting Cookies in the Request Header

When you create a URLRequest to send to WKWebView, you can manually add cookies to the request header. Example code:

swift
var request = URLRequest(url: URL(string: "https://example.com")!) request.addValue("key=value; key2=value2", forHTTPHeaderField: "Cookie") webView.load(request)

Here, "key=value; key2=value2" is the cookie content you want to set.

2. Using WKHTTPCookieStore

Starting from iOS 11, WebKit provides WKHTTPCookieStore, which allows direct management of cookies for WKWebView. You can use this API to add, delete, or observe cookies. Example code:

swift
let webView = WKWebView(frame: .zero) let cookie = HTTPCookie(properties: [ .domain: "example.com", .path: "/", .name: "key", .value: "value", .secure: "TRUE", .expires: NSDate(timeIntervalSinceNow: 3600) ])! webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie) { // Cookie set successfully; load the webpage webView.load(URLRequest(url: URL(string: "https://example.com")!)) }

Using WKHTTPCookieStore, you can not only set cookies but also query and monitor the current cookie state, which helps in better managing cookies within the WebView.

Summary

By using these two main methods, you can flexibly manage cookies in WKWebView, whether by setting them directly in the request header when sending requests or by using WKHTTPCookieStore for more dynamic management. This ensures that web content is displayed correctly based on user identity or other factors, thereby improving the user experience.

2024年8月12日 11:19 回复

你的答案