How to set cookies manually for UIWebView in Swift

I need to set a cookie for web browsing in swift. I found a solution, but it is for objective-c. How to do it in Swift?

Is it possible to set cookie manually using sharedHTTPCookieStorage for UIWebView?

Here is the solution.

+5
source share
1 answer

You can do something like below using NSHTTPCookie and NSHTTPCookieStorage to set a 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 follows:

 NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always 

Swift 3

 HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always 

Note that this was NSHTTPCookieAcceptPolicyAlways in Objective-C and earlier versions of Swift.

Hope this helps :)

+13
source

All Articles