ios 如何在 Swift 中手动为 UIWebView 设置 Cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37136797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To Set a Cookie for a UIWebView manually in Swift
提问by Jacob Smith
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?
我需要在 swift 中为 webview 设置一个 cookie。我找到了一个解决方案,但它是针对 Objective-c 的。如何在 Swift 中做到这一点?
Is it possible to set a cookie manually using sharedHTTPCookieStorage for a UIWebView?
是否可以使用 sharedHTTPCookieStorage 为 UIWebView 手动设置 cookie?
Here is said solution.
这是所说的解决方案。
回答by Ronak Chaniyara
You can do something like below using NSHTTPCookie
and NSHTTPCookieStorage
to set cookie in swift
:
您可以使用NSHTTPCookie
和NSHTTPCookieStorage
设置 cookie来执行以下操作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 :
斯威夫特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:
设置cookieAcceptPolicy
如下:
NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always
Swift 3
斯威夫特 3
HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always
Note that this was NSHTTPCookieAcceptPolicyAlways
in Objective-C and older versions of Swift.
请注意,这是NSHTTPCookieAcceptPolicyAlways
在 Objective-C 和旧版本的 Swift 中。
Hope this helps:)
希望这可以帮助:)