ios – 如何在Swift中手动为UIWebView设置Cookie

前端之家收集整理的这篇文章主要介绍了ios – 如何在Swift中手动为UIWebView设置Cookie前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在 swift中为webview设置一个cookie.我找到了一个解决方案,但它是针对 objective-c的.如何在 Swift中做到这一点?

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

这是解决方案.

解决方法

您可以使用NSHTTPCookie和NSHTTPCookieStorage在swift中设置cookie,如下所示:
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!)
}

斯威夫特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)
    }
}

设置cookieAcceptPolicy如下:

NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always

斯威夫特3

HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always

请注意,这是Objective-C和旧版Swift中的NSHTTPCookieAcceptPolicyAlways.

希望这可以帮助:)

猜你在找的iOS相关文章