Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS WatchKit - how to determine if your code is running in watch extension or the app

Tags:

ios

watchkit

With WatchKit you have your app that runs on the phone, and the watch app that runs as an extension.

If you create a library that contains common code to be used in both the phone app and the watch extension, is there a way to tell if the code is running in the phone app or the watch extension?

I.e.

if ([self isRunningInWatchExtension]) {
    NSLog(@"this is running on watch");
} else {
    NSLog(@"this is running on phone app");
}


- (BOOL)isRunningInWatchExtension {
    ???
}
like image 257
Dan Dosch Avatar asked Mar 30 '15 19:03

Dan Dosch


People also ask

Where does the Watch app extension code run in watchOS 2?

In watchOS 2, not only does the WatchKit extension run on the user's Apple Watch, it is delivered inside the user's Watch app.

What is WatchKit extension?

A WatchKit Extension process that executes the watch app's application logic. This is bundled with your Watch app and runs on the Apple Watch. A Watch app that displays user interface elements and handles navigation.


2 Answers

I've accomplished this by checking the bundle identifier:

if ([[[NSBundle mainBundle] bundleIdentifier] isEqualToString:kAppBundleIdentifier]) {

    // Running in main app
}
else if ([[[NSBundle mainBundle] bundleIdentifier] isEqualToString:kWatchBundleIdentifier]) {

    // Running in extension
}
like image 42
Mike Swanson Avatar answered Sep 29 '22 01:09

Mike Swanson


In target conditionals there are some conditionals that may help you,

#if TARGET_OS_WATCH
//do something for watch
#else
//do something for ios ==> assuming you only support two platforms
#endif
like image 102
Emel Avatar answered Sep 29 '22 01:09

Emel