iOS WatchKit - 如何确定你的代码是 运行 在 watch extension 还是应用程序中

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

使用 WatchKit,您的应用程序可以在 phone 上运行,手表应用程序可以作为扩展程序运行。

如果您创建的库包含要在 phone 应用和手表扩展中使用的通用代码,有没有办法判断 运行 中的代码是否为 [=] 19=] 应用程序或手表扩展程序?

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


- (BOOL)isRunningInWatchExtension {
    ???
}
  • 如果您在通用框架 class 中调用任何自定义方法,这会很容易。您只需要向方法添加额外的方法参数。如果您从 iOS 应用程序或 Watchkit 应用程序调用此方法,则将适当的键值对添加到参数字典中。并在您的框架方法中进行比较。

  • 要从init或任何其他方法确定这一点,那么您仍然可以通过这段代码了解,

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

因此,您需要解析此字符串并获取适当的目标名称。如果它被 iOS 应用程序调用,那么您将获得 'UIKit' 字符串,并且从手表套件应用程序扩展中您将获得 'YourApp WatchKit Extension' 某处的字符串。您还可以参考此 SO 答案来解析此字符串并进行比较 -

我通过检查包标识符完成了此操作:

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

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

    // Running in extension
}

在目标条件句中,有一些条件句可能对您有所帮助,

#if TARGET_OS_WATCH
//do something for watch
#else
//do something for ios ==> assuming you only support two platforms
#endif