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

寵の児 提交于 2020-01-01 05:23:07

问题


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 {
    ???
}

回答1:


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
}



回答2:


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



回答3:


  • This can be easy if you are calling any custom methods in your common framework class. You just need to add additional method parameters to method. And if you are calling this method from iOS app or Watchkit app then add appropriate key-value pair to dictionary for parameters. And compare this in your framework methods.

  • To determine this from init or any other method then you can still get to know by this code,

    NSLog(@"%@",[NSThread callStackSymbols]);
    

So, you need to parse this string and get appropriate target names. If it is called by iOS app then you will get 'UIKit' string and from watch kit app extension you will get 'YourApp WatchKit Extension' string somewhere. You can also refer this SO answer for parsing this string and compare it - https://stackoverflow.com/a/9603733/602997



来源:https://stackoverflow.com/questions/29354990/ios-watchkit-how-to-determine-if-your-code-is-running-in-watch-extension-or-th

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!