0

I'm trying to switch my existing app from UIWebView to WKWebView. The app manages the users login / session outside of the webview. I'm using WKWebsiteDataStore for setting cookies, and its working in iOS 11+ , but in iOS 10 and below app is crashing.

Here is my Code

protected async void LoadCookies()
{
var cookieStore = WKWebsiteDataStore.DefaultDataStore;
var cookies = NSHttpCookieStorage.SharedStorage.Cookies;
var oldcookies = await dataStore.HttpCookieStore.GetAllCookiesAsync();
foreach (var cookie in oldcookies)
{
    await cookieStore.HttpCookieStore.DeleteCookieAsync(cookie);
}
foreach (var cookie in cookies)
{
    await cookieStore.HttpCookieStore.SetCookieAsync(cookie);
}
} 
Swathy
  • 199
  • 1
  • 5
  • 24
  • Can you please share us the stacktrace? Have a look at [this thread](https://stackoverflow.com/questions/49954273/wkwebview-getallcookies-crash-in-ios-11-3/55397755#55397755) may help. – nevermore Jul 27 '20 at 02:50
  • Exception:-Objective-c exception thrown Name:NSInvalidArgumentException Reason[WKWebsiteDataStore httpCookieStore] unrecognized selector sent – Swathy Jul 27 '20 at 05:41

1 Answers1

0

If you read document about httpCookieStore, you will find that httpCookieStore is available since iOS 11.0. That's why your app crash in iOS 10 and below.

You can have a with the solutions in this answer when in iOS 10 and below.

    if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
    {
        foreach (var cookie in cookies)
        {
            await cookieStore.HttpCookieStore.SetCookieAsync(cookie);
        }
    }
    else
    {

        NSMutableUrlRequest request = new NSMutableUrlRequest(new Uri(""));
        request.ShouldHandleCookies = true;
        request.SetValueForKey(new NSString("123"), new NSString("Cookie"));
    }
nevermore
  • 15,432
  • 1
  • 12
  • 30