Reputation: 4795
Starting with watchOS 2, we have an ExtensionDelegate
object, which is analogous to UIApplicationDelegate
(reacts to app lifecycle events).
I want to get a reference to the first Interface Controller object, which will be displayed upon launch, to set a property on it (e.g. pass in a data store object).
According to the docs, the rootInterfaceController
property on WKExtension
hands back the initial controller:
The root interface controller is located in the app’s main storyboard and has the Main Entry Point object associated with it. WatchKit displays the root interface controller at launch time, although the app can present a different interface controller before the launch sequence finishes.
So I try the following in ExtensionDelegate
:
func applicationDidFinishLaunching() {
guard let initialController = WKExtension.sharedExtension().rootInterfaceController else {
return
}
initialController.dataStore = DataStore()
}
Even though the correct Interface Controller is displayed, rootInterfaceController
is nil at this point. Interestingly if I query the same property in the willActivate()
of my Interface Controller, the property is set correctly.
In an iOS app, you can already get the root view controller in applicationDidFinishLaunching()
, and I thought it should work the same for watchOS.
Is there a way to set properties on my Interface Controller before it's displayed (from the outside)? Is this a bug?
Many thanks for the answer!
Upvotes: 8
Views: 2063
Reputation: 65
If you are calling this from within another interface controller, try move the WKExtension.sharedExtension().rootInterfaceController
to the willActivate()
function. It seems like if it is in the awake()
function it sometimes works but is unreliable.
Upvotes: 0
Reputation: 414
You might move your code to applicationDidBecomeActive.
This page describes the states of watch apps. When applicationDidFinishLaunching is invoked, the app is in an inactive state.
Upvotes: 0