Reputation: 11
I try to Upload Pictures from iPhone to my Xamarin-PCL-App. I'm using a Share-Extension and iOS App-groups. My Main-App Observer on changing NSUserDefaults isn't called, when the Extension changes something.
I try to Upload Pictures from iPhone to my Xamarin-PCL-App. I'm using a Share-Extension. I already have implemented the extension, it's working fine. I can choose my App as target in the galery after klicking the share-button. The DidSelectPost() Event of the Extension is called and I can show a Message on the iPhone. Now I want to enter my Main-App to handle the incoming Picture. I added an app-group to my App and the Extension (in the entitlement.plist Files it is already there). Now I should be able to let the Main-App and the Extension communicate via NSUserDefaults, right?
I added the following Code in the Main-Apps AppDelegate in FinishedLaunching:
var userDefaults = new NSUserDefaults("group.de.companyname.appname", NSUserDefaultsType.SuiteName);
userDefaults.AddObserver("rate", NSKeyValueObservingOptions.Prior, note =>
{
NSUserDefaults shared = new NSUserDefaults("group.de.companyname.appname", NSUserDefaultsType.SuiteName);
var value = shared.ValueForKey(new NSString("rate"));
});
It should be called on changes in NSUserDefaults key named "rate". If I change this Value in the Main-App the Event is called.
I added a simple change in the ViewContollers (Type: SLComposeServiceViewController) DidSelectPost Function:
NSUserDefaults shared = new NSUserDefaults("group.de.companyname.appname", NSUserDefaultsType.SuiteName);
shared.SetString("test", "rate");
shared.Synchronize();
My Main-App just doesn't get the changes.
Thanks in Advance!
Upvotes: 1
Views: 686
Reputation: 12723
You should AddObserver in where you changed the value, such as ViewContollers
you used.
Main-Apps AppDelegate:
var userDefaults = NSUserDefaults.StandardUserDefaults;
shared.SetString("testOldData", "rate");
shared.Synchronize();
ViewContollers :
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
NSUserDefaults shared = NSUserDefaults.StandardUserDefaults;
shared.AddObserver(this, "Name", NSKeyValueObservingOptions.OldNew, IntPtr.Zero);
}
//Test Changing the value
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
NSUserDefaults shared = NSUserDefaults.StandardUserDefaults;
shared.SetString("testNewData", "rate");
shared.Synchronize();
}
And when value changed , this method can be invoked:
//When value cahnged this will be invoked
public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
if (keyPath == "Name")
{
Console.WriteLine("--old--" + change.ValueForKey(new NSString("old")));
Console.WriteLine("--new--" + change.ValueForKey(new NSString("new")));
}
else
base.ObserveValue(keyPath, ofObject, change, context);
}
Upvotes: 1