2017-07-25 83 views
3

我正在使用我當前的iPhone音頻應用程序以在CarPlay中受支持。我已經獲得Apple的批准並獲得了開發權,並觀看了視頻「爲CarPlay啓用您的應用程序」(https://developer.apple.com/videos/play/wwdc2017/719/)。在視頻中有演示如何添加CarPlay UI一塊斯威夫特代碼:添加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的屬性「屏幕」總是返回1個元素(主屏幕)。因此,當我的應用程序在模擬器上運行或帶有CarPlay系統的真實汽車上運行時,該應用程序只是空白,並表示「無法連接到」我的應用程序名稱「」(請參閱​​下圖)。儘管我的ViewController有一個簡單的UILabel。

enter image description here

我的問題是:我應該怎麼做才能讓被CarPlay連接我的應用程序?也就是說,我應該如何獲得具有UIUserInterfaceIdiomCarPlay習慣用法的屏幕,而不僅僅是主屏幕?提前致謝。

+0

對本文和我的實驗進行了一些更新:1. CarPlay音頻應用程序無法使用上述updateCarWindow方法中顯示的基於UIScreen的方法。 2.如果我的AppDelegate符合MPPlayableContentDataSource和MPPlayableContentDelegate,並且如果我在AppDelegate.m中實現了數據源和委託方法,那麼我可以看到我的CarPlay UI。 – stspb

回答

1

CarPlay音頻應用程序由MPPlayableContentManager控制。您需要實施MPPlayableContentDelegateMPPlayableContentDatasource協議才能與CarPlay連接。用戶界面由CarPlay控制 - 您需要做的就是爲tab +表格(數據源)提供數據並響應可播放項目(委託)。

+0

感謝您的意見,比利。 CarPlay音頻應用程序無法使用WWDC 2017視頻中顯示的基於UIScreen的方法。這就是爲什麼我的CarPlay應用程序沒有看到任何用戶界面。 – stspb

+0

還有一個問題:要構建CarPlay UI,我應該在作爲NSObject的子類的類中使用MPPlayableContentManager API(MPPlayableContentDataSource&MPPlayableContentDelegate),然後在AppDelegate.m的方法-application:didFinishLaunchingWithOptions:中實例化並初始化該NSObject子類。它是否正確?再次感謝。 – stspb

+0

是的 - 你可以在任何地方初始化這門課。應用程序:didFinishLaunchingWithOptions是一個不錯的選擇,如果你想CarPlay適用於所有用戶。確保你的NSObject子類也是'MPPlayableContentDataSource'&'MPPlayableContentDelegate'的子類。 –