Are Cookies in Uiwebview Accepted

Are cookies in UIWebView accepted?

The UIWebView will automatically store the cookies in the [NSHTTPCookieStorage sharedHTTPCookieStorage] collection, and should be available in all other UIWebViews within your app, during the same app launch. However the UIWebView class does not automatically store cookies for the pages that are loaded between app launches. You need to manually store cookies when the app is moved into the background and reload the values when the app is brought back into the foreground.

Place the following code in your AppDelegate class:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Other existing code

[self loadHTTPCookies];
return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
//Other existing code

[self saveHTTPCookies];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
[self loadHTTPCookies];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
//Other existing code
[self saveHTTPCookies];
}

-(void)loadHTTPCookies
{
NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

for (int i=0; i < cookieDictionary.count; i++)
{
NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}

-(void)saveHTTPCookies
{
NSMutableArray *cookieArray = [[NSMutableArray alloc] init];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookieArray addObject:cookie.name];
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];
[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];
[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];
[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];
[cookieProperties setObject:[NSNumber numberWithUnsignedInteger:cookie.version] forKey:NSHTTPCookieVersion];
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];
[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

Are cookies in UIWebView accepted?

The UIWebView will automatically store the cookies in the [NSHTTPCookieStorage sharedHTTPCookieStorage] collection, and should be available in all other UIWebViews within your app, during the same app launch. However the UIWebView class does not automatically store cookies for the pages that are loaded between app launches. You need to manually store cookies when the app is moved into the background and reload the values when the app is brought back into the foreground.

Place the following code in your AppDelegate class:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Other existing code

[self loadHTTPCookies];
return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
//Other existing code

[self saveHTTPCookies];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
[self loadHTTPCookies];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
//Other existing code
[self saveHTTPCookies];
}

-(void)loadHTTPCookies
{
NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

for (int i=0; i < cookieDictionary.count; i++)
{
NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}

-(void)saveHTTPCookies
{
NSMutableArray *cookieArray = [[NSMutableArray alloc] init];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookieArray addObject:cookie.name];
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];
[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];
[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];
[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];
[cookieProperties setObject:[NSNumber numberWithUnsignedInteger:cookie.version] forKey:NSHTTPCookieVersion];
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];
[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];
[[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!

Getting all cookies from WKWebView

Finally, httpCookieStore for WKWebsiteDataStore landed in iOS 11.

https://developer.apple.com/documentation/webkit/wkwebsitedatastore?changes=latest_minor

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

Webpage cookies are not detected by UIWebView

A few ideas:

The device's Safari "Block Cookies" settings override any changes to the cookieAcceptPolicy. The default policy of this setting on the device is "Allow from Websites I Visit," which depending on your iOS device's version, allows third-party cookies. Testing with iOS 9.3.x shows that third party cookies are persisted in a UIWebView with the default settings, but do not persist with the settings "Allow from Current Website Only" or "Always Block."

Check if the device persists your cookie with the different Safari cookie settings.

Additionally, does your cookie have an expiration date set? I've found that cookies without an expiration date set are treated as session cookies in a UIWebView, which only persist with the lifecycle of the web view that received it.



Related Topics



Leave a reply



Submit