0

I want to add a cookie to IOS webView application with swift 4.2 in XCode but it does not work. Below is one of the code examples I tried to apply and it does not work. Can anyone help me?

let cookieProps:[HTTPCookiePropertyKey:Any]=[
    HTTPCookiePropertyKey.domain:"https://system.fast-apps.com",
    HTTPCookiePropertyKey.path:"/",
    HTTPCookiePropertyKey.name:"isNative",
    HTTPCookiePropertyKey.value:"IwBhE4g"]

    if let cookie = HTTPCookie(properties: cookieProps){    
            HTTPCookieStorage.shared.setCookie(cookie)
    }
Radosław Cybulski
  • 2,952
  • 10
  • 21
Edgar
  • 11
  • 3

1 Answers1

0

You can easily add cookies to the cookie storage, by implementing the method below:

var cookies: [HTTPCookie?] = [] {
    didSet {
        cookies.compactMap { $0 }.forEach {
            HTTPCookieStorage.shared.setCookie($0)
        }
    }
}

func addCookie(for url: URL, key: String, value: AnyObject, path: String = "/", isSecure: Bool = true, expirationTime: TimeInterval) {
    cookies.append(HTTPCookie(properties: [
        .originURL: url,
        .path: path,
        .name: key,
        .value: value,
        .secure: isSecure ? "TRUE" : "FALSE",
        .expires: Date(timeIntervalSinceNow: expirationTime)
    ]))
}

Then, use it as follows:

addCookie(for: url, key: "someKey", value: someValue, expirationTime: 10000)
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174