我需要在
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.
希望这可以帮助:)