How to manage cookies with UIWebView in Swift
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)
}
iOS How to add cookie to each UIWebView request?
Thanks for your help. Problem was solved by creating a cookie with specific domain:
final class FieldServiceViewController: UIViewController, DLHasHomeTitleView {
private let fieldServiceEndPoint = Bundle.main.object(forInfoDictionaryKey: "FIELD_SERVICE_ENDPOINT") as! String
private var webView = UIWebView()
private var sessionID = String()
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
_ = JSONAPI.getSessionID().subscribe(onNext: { [weak self] sessionID in
guard let `self` = self else { return }
self.sessionID = sessionID
let urlString = "https://\(self.fieldServiceEndPoint)"
let url = URL(string: urlString)
let request = URLRequest(url: url!)
let cookie = HTTPCookie(properties: [
.name: "JSESSIONID",
.value: sessionID,
.path: "/",
.domain: self.fieldServiceEndPoint])
HTTPCookieStorage.shared.setCookie(cookie!)
self.webView.loadRequest(request)
})
}
Getting all cookies from WKWebView
Finally, httpCookieStore
for WKWebsiteDataStore
landed in iOS 11.
https://developer.apple.com/documentation/webkit/wkwebsitedatastore?changes=latest_minor
How to delete all cookies of UIWebView?
According to this question, you can go through each cookie in the "Cookie Jar" and delete them, like so:
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];
Can I set the cookies to be used by a WKWebView?
Edit for iOS 11+ only
Use WKHTTPCookieStore:
let cookie = HTTPCookie(properties: [
.domain: "example.com",
.path: "/",
.name: "MyCookieName",
.value: "MyCookieValue",
.secure: "TRUE",
.expires: NSDate(timeIntervalSinceNow: 31556926)
])!
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
Since you are pulling them over from HTTPCookeStorage, you can do this:
let cookies = HTTPCookieStorage.shared.cookies ?? []
for cookie in cookies {
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
}
Old answer for iOS 10 and below
If you require your cookies to be set on the initial load request, you can set them on NSMutableURLRequest. Because cookies are just a specially formatted request header this can be achieved like so:
WKWebView * webView = /*set up your webView*/
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/index.html"]];
[request addValue:@"TeskCookieKey1=TeskCookieValue1;TeskCookieKey2=TeskCookieValue2;" forHTTPHeaderField:@"Cookie"];
// use stringWithFormat: in the above line to inject your values programmatically
[webView loadRequest:request];
If you require subsequent AJAX requests on the page to have their cookies set, this can be achieved by simply using WKUserScript to set the values programmatically via javascript at document start like so:
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: @"document.cookie = 'TeskCookieKey1=TeskCookieValue1';document.cookie = 'TeskCookieKey2=TeskCookieValue2';"
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
// again, use stringWithFormat: in the above line to inject your values programmatically
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
webViewConfig.userContentController = userContentController;
WKWebView * webView = [[WKWebView alloc] initWithFrame:CGRectMake(/*set your values*/) configuration:webViewConfig];
Combining these two techniques should give you enough tools to transfer cookie values from Native App Land to Web View Land. You can find more info on the cookie javascript API on Mozilla's page if you require some more advanced cookies.
Yeah, it sucks that Apple is not supporting many of the niceties of UIWebView. Not sure if they will ever support them, but hopefully they will get on this soon. Hope this helps!
Disable Cookies UIWebView Swift iOS
Try to This
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies! {
storage.deleteCookie(cookie)
}
NSUserDefaults.standardUserDefaults().synchronize()
Clear webView cookies (Swift)
I made it by
let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in cookieJar.cookies! {
// print(cookie.name+"="+cookie.value)
cookieJar.deleteCookie(cookie)
}
Swift 4
func removeCookies(){
let cookieJar = HTTPCookieStorage.shared
for cookie in cookieJar.cookies! {
cookieJar.deleteCookie(cookie)
}
}
Related Topics
Could Not Find Module for Target 'X86_64-Apple-Ios-Simulator'
How to Create Border in Uibutton
Xcode 5.1: Libcordova.A Architecture Problems
Locking a Uisearchbar to the Top of a Uitableview Like Game Center
Uiview Touch Event in Controller
Linking Child View Controllers to a Parent View Controller Within Storyboard
How to Add a Button to Uinavigationbar
Why Is There an Frame Rectangle and an Bounds Rectangle in an Uiview
Why Is My iOS App Not Showing Up in Other Apps' "Open In" Dialog
iOS - 'Myproject-Swift.H' File Not Found When Running Unit Tests for Swift
Cookie Sharing Between Multiple Wkwebviews
Find Current Country from iPhone Device
Could Not Launch Process Launch Failed: Timed Out Waiting for App to Launch
Contentview Not Indenting in iOS 6 Uitableviewcell Prototype Cell
How to Implement a Box or Gaussian Blur on iOS
Storing Uicolor Object in Core Data
Fbsdkloginmanager Loginwithpublishpermissions Always Returns Iscancelled=Yes
Import Swift Class in Objective-C, <Mymodule>-Swift.H File Not Found