You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多平台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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:52:37