I need to set a cookie for a webview in swift. I found a solution, but it is for objective-c. How to do it in Swift?
Is it possible to set a cookie manually using shared
You can do something like below using NSHTTPCookie
and NSHTTPCookieStorage
to set cookie in swift
:
let URL = "example.com"
let ExpTime = NSTimeInterval(60 * 60 * 24 * 365)
func setCookie(key: String, value: AnyObject) {
var cookieProps = [
NSHTTPCookieDomain: URL,
NSHTTPCookiePath: "/",
NSHTTPCookieName: key,
NSHTTPCookieValue: value,
NSHTTPCookieSecure: "TRUE",
NSHTTPCookieExpires: NSDate(timeIntervalSinceNow: ExpTime)
]
var cookie = NSHTTPCookie(properties: cookieProps)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie!)
}
Swift 3 :
func setCookie(key: String, value: AnyObject) {
let cookieProps: [HTTPCookiePropertyKey : Any] = [
HTTPCookiePropertyKey.domain: URL,
HTTPCookiePropertyKey.path: "/",
HTTPCookiePropertyKey.name: key,
HTTPCookiePropertyKey.value: value,
HTTPCookiePropertyKey.secure: "TRUE",
HTTPCookiePropertyKey.expires: NSDate(timeIntervalSinceNow: ExpTime)
]
if let cookie = NSHTTPCookie(properties: cookieProps) {
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie)
}
}
set cookieAcceptPolicy
as follow:
NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always
Swift 3
HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always
Note that this was NSHTTPCookieAcceptPolicyAlways
in Objective-C and older versions of Swift.
Hope this helps:)