I wanted to make a test app for the Apple watch in which you can set some String on your phone, and then it will be displayed on the Apple Watch. I decided to use NSUserDefaults class to store this data.
In my view controller for the iPhone I have a method which takes the input and stores into local storage:
- (IBAction)saveInfo:(id)sender {
NSString *userInput = [myTextField text];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:userInput forKey:@"savedUserInput"];
[defaults synchronize];
self.myLabel.text = [defaults stringForKey:@"savedUserInput"];
}
And in my watch interface controller I have a method that retrieves the data and displays it:
- (IBAction)showText2 {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize];
self.myLabel2.text = [defaults stringForKey:@"savedUserInput"];
}
Except for some reason the data I am trying to retrieve is shown as null, and the label is not being updated.
+standardUserDefaults
returns an NSUserDefaults
object that only saves information for the current process.
If you want to create an NSUserDefaults
object that shares data between your iOS app and one of its extensions, then you'll need to set up an app group container and use that as the basis for sharing information.
From the linked documentation:
After you enable app groups, an app extension and its containing app can both use the NSUserDefaults API to share access to user preferences. To enable this sharing, use the initWithSuiteName: method to instantiate a new NSUserDefaults object, passing in the identifier of the shared group. For example, a Share extension might update the user’s most recently used sharing account, using code like this:
// Create and share access to an NSUserDefaults object. NSUserDefaults *mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.example.domain.MyShareExtension"]; // Use the shared user defaults object to update the user's account. [mySharedDefaults setObject:theAccountName forKey:@"lastAccountName"];
NOTE: With watch OS2 you can no longer use shared group containers.