Xamarin Forms - iOS - storing cookies between application runs

Palkos 1 Reputation point
2021-07-02T13:42:33.543+00:00

I am trying to implement a user logon using Xamarin for Android and iOS. I am using WebView for displaying the back end user logon page. When logon is successful session cookies are saved in the cookie storage which can be used for automatic log on up to the point when tokens are expired.

For Android everything is working fine, when I close the app and start it again it automatically logs me in.

For iOS situation is different and I am redirected to the logon page. This means the cookies are deleted between two runs of the application.

Any suggestions how to setup iOS so it keeps the cookies between multiple runs of the app?

Many thanks for help in advance.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,326 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Kyle Wang 5,531 Reputation points
    2021-07-05T02:53:53.687+00:00

    Hi Palkos-6616,

    Welcome to our Microsoft Q&A platform!

    Actually, in my test, cookies will be saved without any other operations.

    To save the cookies, try to set "AcceptPolicy" to "NSHttpCookieAcceptPolicy.Always".

    NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always  
    

    Add the following code to renderer's "OnElementChanged". Here is the reference link.

    // Set cookies here  
    var cookieUrl = new Uri(@"https://www.microsoft.com");  
    var cookieJar = NSHttpCookieStorage.SharedStorage;  
    cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;  
    foreach (var aCookie in cookieJar.Cookies)  
    {  
        cookieJar.DeleteCookie(aCookie);  
    }  
      
    var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);  
    IList<NSHttpCookie> eCookies =  
        (from object jCookie in jCookies  
            where jCookie != null  
            select (Cookie)jCookie  
            into netCookie  
            select new NSHttpCookie(netCookie)).ToList();  
    cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);  
    

    And you can call HttpCookieStore.GetAllCookies to get the cookies.

    Regards,
    Kyle


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.