How can I set cookies on a WKWebView in a SwiftUI app?

  Kiến thức lập trình

I’m trying to set cookies on a WKWebView so a user is logged in, however, the cookies don’t seem to be recognized making me think they are either not set correctly or the cookies themselves are not correct/valid. In any case the user isn’t logge, which they are when setting those cookies manually in a regular browser outside the simulator (after refreshing the page).

The WebView looks like this:

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    let url: URL

    func makeUIView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()

        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
        let expirationDate = formatter.date(from: "2024/07/20 23:33:41")

        let cookies = [
            HTTPCookie(properties: [
                .name: "AUTH_SESSION_ID",
                .value: "cookie-value",
                .domain: "example.com",
                .path: "/path",
                .init(rawValue: "HttpOnly"): true,
                .secure: true,
                .sameSitePolicy: "None"
            ],
            HTTPCookie(properties: [
                .name: "IDENTITY",
                .value: "cookie-value",
                .domain: "example.com",
                .path: "/path",
                .init(rawValue: "HttpOnly"): true,
                .secure: true,
                .sameSitePolicy: "None"
            ],
            HTTPCookie(properties: [
                .name: "SESSION",
                .value: "cookie-value",
                .domain: "example.com",
                .path: "/path",
                .expires: expirationDate as NSDate?
                .init(rawValue: "HttpOnly"): false,
                .secure: true,
                .sameSitePolicy: "None"
            ]
        ]

        for cookie in cookies {
            configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
        }

        return WKWebView(frame: CGRect.zero, configuration: configuration)
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        let request = URLRequest(url: url)
        webView.load(request)
    }
}

And it is used in the ContentView like this:

struct ContentView: View {
    var body: some View {
        TabView {
            WebView(url: URL(string: "https://example.com/home")!)
                .tabItem {
                    Label("Home", systemImage: "house")
                }

            WebView(url: URL(string: "https://example.com/me")!)
                .tabItem {
                    Label("Me", systemImage: "person")
                }
        }
    }
}

Curiously, when printing the cookies at the end of the makeUIView function (before returning the webView) there are no cookies, but after switching to the Me tab there are.

configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
    print("Got (cookies.count) cookies")
    for cookie in cookies {
        print("Cookie: (cookie.name) = (cookie.value)")
    }
}

How can I make valid cookies and set them on the web view? Or how can I debug what is going wrong? I can’t use Safari to look at the storage of the web view to check if the cookies are set properly and if they contain the right values.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT