[Tip] Xamarin.iOS: Sharing a dictionary with the Apple Watch
Steps to share a dictionary between the apple watch (or any app extension app ) and a device.
1) Create a group in the Apple Provisioning Portal. (eg. group.com.mycompany.myapp)
2) Add the group to both apps: the extension and the main app (there is no need to add the group to the actual watch app).
3) Activate the group in the Entitlements.plist for each project (main app and extension)
4) Start sharing code
Save:
var defaults = new NSUserDefaults (“GroupName”, NSUserDefaultsType.SuiteName);
defaults.SetString (json,”key”);
defaults.Synchronize ();
Retrieve:
var defaults = new NSUserDefaults (“GroupName”, NSUserDefaultsType.SuiteName);
defaults.Synchronize ();
var json = defaults.StringForKey (“key”);
5) Bonus: it didn't work in the simulator for me. I wasted a lot of time trying to figure out what I was doing wrong.
6) Extra bonus: use preprocessor conditions if you want to fake it in the simulator:
string GetJson() {
#if DEBUG
return JsonConvert.SerializeObject(new YourClass {
…Properties…
} );
#endif
var defaults = new NSUserDefaults (“GroupName”, NSUserDefaultsType.SuiteName);
defaults.Synchronize ();
var json = defaults.StringForKey (“key”);
return json;
}