xamarin.formsxamarin.iosios-extensions

How to share Preferences in a Xamarin.Forms project between an iOS and iOS extensions?


I'm trying to get a string (UserID) using Preferences.Get (Xamarin.Essentials) on a PushNotification.Extension project, but as the Preferences.Set happens in the Xamarin iOS project, I'm always getting an empty string in the extensions project.

Is there a way to share this preference between the iOS project and the iOS.extension?

public string UserID
{
    get
    {
        return Preferences.Get(nameof(UserID), UserIDDefault);
    }
    set
    {
        Preferences.Set(nameof(UserID), value);
    }
}

Solution

  • According to Apple docs , please follow the steps to enable data-sharinig .

    1. Enable App Groups Capabilities , refer to App Group Capabilities in Xamarin.iOS.

    2. Add the app to the App Group .

    3. Use NSUserDefaults and init it with the name of the extension bundle identifier.

    //Save 
    var defaults = new NSUserDefaults(@"com.example.domain.MyShareExtension");
    defaults.SetString("value","Mykey");
    defaults.Synchronize();
    
    //Get
    var defaults = new NSUserDefaults(@"com.example.domain.MyShareExtension");
    var value = defaults.ValueForKey("Mykey");