ios 如何在 Swift 中使用 UIWebView 管理 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27543817/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:04:14  来源:igfitidea点击:

How to manage cookies with UIWebView in Swift

iosobjective-ccookiesswiftwebview

提问by ernestocattaneo

What about have a topic where people can easily see how to manage cookies in a webview using the new language Swift? If you check in internet you won't find anything interesting when you need to implement this. Even the documentation by apple is poor.

有一个主题让人们可以轻松地看到如何使用新语言 Swift 在 web 视图中管理 cookie?如果您在互联网上查看,当您需要实施此功能时,您将找不到任何有趣的东西。甚至苹果的文档也很差。

Do anybody know how to handle these process in Swift? This is what I found but in Obj-C:

有人知道如何在 Swift 中处理这些过程吗?这是我在 Obj-C 中发现的:

SEE COOKIES STORED

查看存储的 Cookie

NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [cookieJar cookies]) {
NSLog(@"%@", cookie);
}

DELETE STORED COOKIES

删除存储的 Cookie

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];

It would be nice for everybody if we can give for one time an answer to this! Cheers!

如果我们可以一次回答这个问题,对每个人都会很好!干杯!

回答by Dharmesh Kheni

Try this code:

试试这个代码:

SEE COOKIES STORED

查看存储的 Cookie

    if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies {
        for cookie in cookies {
            NSLog("\(cookie)")
        }
    }

DELETE STORED COOKIES

删除存储的 Cookie

    var storage : NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    for cookie in storage.cookies  as! [NSHTTPCookie]{
        storage.deleteCookie(cookie)
    }

swift 2.0

快速 2.0

let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies! {
 storage.deleteCookie(cookie)
}

Swift 3.0

斯威夫特 3.0

if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        NSLog("\(cookie)")
    }
}

let storage = HTTPCookieStorage.shared
for cookie in storage.cookies! {
    storage.deleteCookie(cookie)
}

回答by VelocityPulse

swift 3 clear version

swift 3 清晰版

Save cookies

保存饼干

func saveCookies() {
    guard let cookies = HTTPCookieStorage.shared.cookies else {
        return
    }
    let array = cookies.flatMap { (cookie) -> [HTTPCookiePropertyKey: Any]? in
        cookie.properties
    }
    UserDefaults.standard.set(array, forKey: "cookies")
    UserDefaults.standard.synchronize()
}

Load cookies:

加载饼干

func loadCookies() {
    guard let cookies = UserDefaults.standard.value(forKey: "cookies") as? [[HTTPCookiePropertyKey: Any]] else {
        return
    }
    cookies.forEach { (cookie) in
        guard let cookie = HTTPCookie.init(properties: cookie) else {
            return
        }
        HTTPCookieStorage.shared.setCookie(cookie)
    }
}

You can call these functions like the following code

您可以像下面的代码一样调用这些函数

func webViewDidStartLoad(_ webView: UIWebView) {
    loadCookies()
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    saveCookies()
}

Do not forget to have a delegate of your WebView for webViewDidStartLoadand webViewDidFinishLoad

不要忘记为webViewDidStartLoadwebViewDidFinishLoad 指定一个 WebView委托

回答by magnuskahr

swift 2.0

快速 2.0

let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies! {
 storage.deleteCookie(cookie)
}
NSUserDefaults.standardUserDefaults().synchronize()

回答by zzpaf

Thanks for the swift "translation"... Just needed to change the deletion to as! to force downcast:

感谢您的快速“翻译”......只需要将删除更改为!强迫垂头丧气:

var storage : NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies  as! [NSHTTPCookie]
{
    storage.deleteCookie(cookie)
}
NSUserDefaults.standardUserDefaults()

回答by mathema

Here is the complete answer with how to capture cookies with UIWebView's delegate function:

以下是如何使用 UIWebView 的委托函数捕获 cookie 的完整答案:

func webViewDidFinishLoad(_ webView: UIWebView) {
    if let cookies = HTTPCookieStorage.shared.cookies {
        for cookie in cookies {
            print("cookie= \(cookie)")
        }
    }
}

Keep in mind that cookies will saved as default and this delegate function calls every movement that finished with webview load. (It's also updated with Swift 3.0.1)

请记住,cookie 将保存为默认值,并且此委托函数调用完成 webview 加载的每个动作。(它也随Swift 3.0.1更新)

回答by pansora abhay

If you are working on swift 4then this code will disable cookiesand also remove the URL cache.

如果您正在使用swift 4,那么此代码将禁用cookie删除 URL 缓存

let cookieJar : HTTPCookieStorage = HTTPCookieStorage.shared
for cookie in cookieJar.cookies! as [HTTPCookie]{
    NSLog("cookie.domain = %@", cookie.domain)
     cookieJar.deleteCookie(cookie)
}

URLCache.shared.removeAllCachedResponses() 
URLCache.shared.diskCapacity = 0 
URLCache.shared.memoryCapacity = 0

回答by BYCHKOVSKIY

Logout for api VKontakte, swift 3+

注销 api VKontakte, swift 3+

let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { (records) in
    for record in records {
        if record.displayName.contains("facebook") {
            dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: [record], completionHandler: {
                print("Deleted: " + record.displayName);
            })
        }
    }
}

回答by ifedapo olarewaju

swift 3

迅捷 3

    let storage = HTTPCookieStorage.shared

    for cookie in storage.cookies! {
        storage.deleteCookie(cookie)
    }