我正在开发要在 CarPlay 中支持的当前 iPhone 音频应用程序。我已经获得了 Apple 的批准并获得了开发授权,并观看了视频“为 CarPlay 启用您的应用程序”(https://developer.apple.com/videos/play/wwdc2017/719/)。在视频中,有一段 Swift 代码演示了如何添加 CarPlay UI:
func updateCarWindow()
{
guard let screen = UIScreen.screens.first(where:
{ $0.traitCollection.userInterfaceIdiom == .carPlay })
else
{
// CarPlay is not connected
self.carWindow = nil;
return
}
// CarPlay is connected
let carWindow = UIWindow(frame: screen.bounds)
carWindow.screen = screen
carWindow.makeKeyAndVisible()
carWindow.rootViewController = CarViewController(nibName: nil, bundle: nil)
self.carWindow = carWindow
}
我将其重写为 Objective-C 版本,如下所示:
- (void) updateCarWindow
{
NSArray *screenArray = [UIScreen screens];
for (UIScreen *screen in screenArray)
{
if (screen.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomCarPlay) // CarPlay is connected.
{
// Get the screen's bounds so that you can create a window of the correct size.
CGRect screenBounds = screen.bounds;
UIWindow *tempCarWindow = [[UIWindow alloc] initWithFrame:screenBounds];
self.carWindow.screen = screen;
[self.carWindow makeKeyAndVisible];
// Set the initial UI for the window.
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *rootViewController = [storyboard instantiateViewControllerWithIdentifier:@"VC"];
self.carWindow.rootViewController = rootViewController;
self.carWindow = tempCarWindow;
// Show the window.
self.carWindow.hidden = NO;
return;
}
}
// CarPlay is not connected.
self.carWindow = nil;
}
但是我发现 UIScreen 的属性“screens”总是返回 1 个元素(主屏幕),无论是在真实设备还是模拟器上进行测试。因此,当我的应用程序在模拟器或带有 CarPlay 系统的真车上运行时,应用程序只是空白并显示“无法连接到“我的应用程序名称””(见下图)。我的 ViewController 虽然有一个简单的 UILabel。
我的问题是:我应该怎么做才能让 CarPlay 连接我的应用程序?也就是说,我应该如何获得具有 UIUserInterfaceIdiomCarPlay 习语的屏幕,而不仅仅是主屏幕?提前非常感谢。