I want to make a remote control type of watchkit app where I can trigger certain things on screen in my parent app via the watch. When the watch app starts, I display a label stating that it is connecting with the app.
I create a WCSession and send a message to the app to see if the app is in the foreground. It turns out, even if the app is in the background, it still sends a response back. My watch app therefore thinks the app is ready.
I've tried querying [UIApplication sharedApplication].applicationState but this always came back as nil and a warning during debugging stating that UIApplication can only be called on the main thread.
I also read a function similar to openparentapplication is the way to do it, but that was deprecated I believe as of WatchOS 2 or 3.
How am I able to tell the watch that the application is in the foreground so I know its safe to send my commands to the app to update elements in it's UI?
As far as I know, there is no default method for this.
However, one feasible method would be sending a message to the Watch app both from - (void)applicationDidBecomeActive:(UIApplication *)application;
and - (void)applicationWillResignActive:(UIApplication *)application;
to signal the watch app whether it can "remote control" the iOS app or not.
So in your WatchKit
app, you should declare a boolean variable to store the state of your iOS app (something like isPhoneAppActive
) and from the iOS app send messages using the WatchConnectivity
framework with the new value of this variable. From applicationWillResignActive
send a false
value, while from applicationDidBecomeActive
send true
. Then only call your "remote control" functions from the Watch app if isPhoneAppActive == true
.
Of course you can use the same approach with slight changes. For example if your phone app has a lot of other capabilities and hence it will likely often be moving into and out of background mode without the Watch app being used, it would make more sense to store the application state inside the iOS app and when needed, check this stored state from the watch app by sending a message using the WatchConnectivity
framework and in its reply from iOS sending back the application state.