Forum Xamarin.iOS
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

How to load cookies on iOS 13?

MikilllMikilll Member ✭✭✭

Hello,
How to load cookies in iOS 13. In previous versions of iOS I was using this code:

var cookieArray = NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("cookieArray")) as NSMutableArray;
if (cookieArray == null)
{
    return;
}

for (nuint i = 0; i < cookieArray.Count; i++)
{
    var cookieDict = NSUserDefaults.StandardUserDefaults.ValueForKey(cookieArray.GetItem<NSString>(i)) as NSMutableDictionary;
    var cookie = NSHttpCookie.CookieFromProperties(cookieDict);
    NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
}

However, on iOS 13 cookieDict is always null. On previous iOS versions, it was working fine. Does someone have any solution how to implement this on iOS 13?

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    The code you post above demonstrates how to retrieve cookies from NSUserDefaults.
    And it seems you stored the cookies depending on the values of cookieArray. It could miss some cookies if you mistake some keys.
    You can store the whole cookies like:

    // Convert the property arraies to data
    var cookieData = NSKeyedArchiver.ArchivedDataWithRootObject(propertyArray);
    
    NSUserDefaults.StandardUserDefaults.SetValueForKey(cookieData, new NSString("cookieArray"));
    NSUserDefaults.StandardUserDefaults.Synchronize();
    
    // Retrieve it like
    var cookieData = NSUserDefaults.StandardUserDefaults.DataForKey(new NSString("cookieArray"));
    var propertyArray = NSKeyedUnarchiver.UnarchiveObject(cookieData) as NSArray;
    if (propertyArray == null)
    {
        return;
    }
    
    for (nuint i=0; i<propertyArray.Count; i++)
    {
        var cookieDict = propertyArray.GetItem<NSDictionary>(i);
        var cookie = NSHttpCookie.CookieFromProperties(cookieDict);
    }
    
Sign In or Register to comment.