多平台App适配Apple TV时,如何排除CarPlay相关代码?
解决Apple TV平台编译「No such module 'CarPlay'」错误
因为Apple TV平台不支持CarPlay框架,而你的多平台项目未为TV单独创建Target,只需通过条件编译指令将CarPlay相关代码限定在iOS和Mac Catalyst平台下编译,Apple TV编译时会自动忽略这部分代码,即可解决报错问题。
具体修改后的代码如下:
#if os(iOS) || targetEnvironment(macCatalyst) import CarPlay class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate { var interfaceController: CPInterfaceController? func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene, didConnect interfaceController: CPInterfaceController) { self.interfaceController = interfaceController let nowPlaying = CPNowPlayingTemplate.shared self.interfaceController?.setRootTemplate(nowPlaying, animated: true, completion: {_, _ in }) } private func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene, didDisconnect interfaceController: CPInterfaceController) { self.interfaceController = nil } } #endif
核心说明:
#if os(iOS) || targetEnvironment(macCatalyst)会限定代码仅在iOS设备或Mac Catalyst环境下编译,Apple TV编译流程会直接跳过这段代码,也就不会触发「找不到CarPlay模块」的错误。- 若项目中还有其他CarPlay相关逻辑(比如AppDelegate里的调用、Info.plist中的CarPlay场景配置),同样需要用条件编译或配置变体的方式,确保Apple TV环境下不加载这些内容。
内容的提问来源于stack exchange,提问作者Halpo
相关产品推荐
相关产品推荐

