How To Set a Cookie for a UIWebView manually in Swift

后端 未结 1 2129

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

相关标签:
1条回答
  • 2021-02-20 17:16

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

    0 讨论(0)
提交回复
热议问题