Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

ios - How to manage cookies with UIWebView in Swift

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.

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

SEE COOKIES STORED

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this code:

SEE COOKIES STORED

    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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...