Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Set a Cookie for a UIWebView manually in Swift

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.

like image 857
Jacob Smith Avatar asked May 10 '16 11:05

Jacob Smith


1 Answers

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:)

like image 139
Ronak Chaniyara Avatar answered Sep 25 '22 18:09

Ronak Chaniyara