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 sharedHTTPCookieStorage for a UIWebView?
Here is said solution.
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:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With