I couldn't find an easy way to update the view in my iPhone app when I push a button on the AppleWatch App yet.
I tried it with NSUserDefaults Observer like this:
iPhone App Viewcontroller(inside ViewDidLoad()):
// Create and share access to an NSUserDefaults object.
mySharedDefaults = NSUserDefaults(suiteName: "group.sharedTest")
//Add Observer
NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: "test", options: NSKeyValueObservingOptions.New, context: nil)
In the Watchkit Extensions InterfaceController I added an IBAction with the button with this code:
mySharedDefaults!.setObject("testValue", forKey: "test")
mySharedDefaults!.synchronize()
But when I press the button, nothing happens! If I set an object inside my iPhone ViewController it works, but not if it is updated via the app! Can someone help me?
You weren't lucky because when you wrote your question there wasn't API for this in iOS SDK. Three days ago, 10th December 2014 Apple released iOS 8.2 beta 2 SDK with two, important for this task, methods.
In WatchKit Framework,
WKInterfaceController
classBy calling this method iOS will run your app in the background and AppDelegate of app will receive this message
This is second method added in iOS SDK Beta 2 (in terms of this question) in UIKit Framework,
UIApplicationDelegate
class.You can use NSDictionary and reply block to communicate Watch app and iOS app.
Example
In your
WKInterfaceController
subclassand then in your iOS AppDelegate class
When you tap button on Apple Watch simulator your iOS app in iOS Simulator will be launched, and you should be able to see NSLog's in proper places.
Note
This solution works for transporting objects between Watch and iOS apps. But if you plan to transport more data, access images, file etc, you should use
Shared app group
. You set shared app group in Capabilities in your Xcode Project file. UsecontainerURLForSecurityApplicationGroupIdentifier
(NSFileManager
class) to get URLs to files in shared group.If you want to share Preferences
initWithSuiteName
fromNSUserDefaults
is what you are looking for.