如何在Swift中管理带有UIWebView的cookie

时间:2022-02-10 17:19:44

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在webview中管理cookie呢?如果你上网查,你就不会发现任何有趣的东西,当你需要实现这个。甚至苹果的文件也很糟糕。

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

有谁知道如何用Swift处理这些流程吗?这是我在objc - c中发现的:

SEE COOKIES STORED

看到cookie存储

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

DELETE STORED COOKIES

删除存储饼干

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!

如果我们能给大家一个答案,那对大家都好!干杯!

8 个解决方案

#1


36  

Try this code:

试试这段代码:

SEE COOKIES STORED

看到cookie存储

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

DELETE STORED COOKIES

删除存储饼干

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

#2


5  

swift 2.0

斯威夫特2.0

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

#3


5  

swift 3 clear version

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 :

加载cookie:

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 webViewDidStartLoad and webViewDidFinishLoad

不要忘记为webViewDidStartLoad和webViewDidFinishLoad设置一个WebView的委托

#4


3  

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

谢谢你迅速的翻译。只需要将删除更改为as!力沮丧:

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

#5


2  

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 load完成的所有移动。(它还更新了Swift 3.0.1)

#6


1  

If you are working on swift 4 then this code will disable cookies and 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

#7


0  

swift 3

斯威夫特3

    let storage = HTTPCookieStorage.shared

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

#8


0  

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);
            })
        }
    }
}

#1


36  

Try this code:

试试这段代码:

SEE COOKIES STORED

看到cookie存储

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

DELETE STORED COOKIES

删除存储饼干

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

#2


5  

swift 2.0

斯威夫特2.0

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

#3


5  

swift 3 clear version

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 :

加载cookie:

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 webViewDidStartLoad and webViewDidFinishLoad

不要忘记为webViewDidStartLoad和webViewDidFinishLoad设置一个WebView的委托

#4


3  

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

谢谢你迅速的翻译。只需要将删除更改为as!力沮丧:

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

#5


2  

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 load完成的所有移动。(它还更新了Swift 3.0.1)

#6


1  

If you are working on swift 4 then this code will disable cookies and 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

#7


0  

swift 3

斯威夫特3

    let storage = HTTPCookieStorage.shared

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

#8


0  

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);
            })
        }
    }
}