为 CarPlay 创建列表

Create a list for CarPlay

所以我目前必须手动将新电台添加到我们的 CarPlay 应用程序。然而,我们有一个 JSON,我们的应用程序将其用于 iPhone 和 iPad。所以我想知道如何创建一个使用这些信息的列表而不是我手动创建它。

func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene, didConnect interfaceController: CPInterfaceController) {
   
    
    let DRN1 = CPListItem(text: "DRN1", detailText: "Perth's No.1 Online Station.")
    let Hits = CPListItem(text: "DRN1 Hits", detailText: "Top 40 songs and yesturdays hits.")
    let United = CPListItem(text: "DRN1 United", detailText: "Perth's Dedicated LGBTIQA+ Station.")
    let Dance = CPListItem(text: "DRN1 Dance", detailText: "Playing the hottest dance tracks.")
    
   
    
    if #available(iOS 14.0, *) {
        let nowplay = CPNowPlayingTemplate.shared
        
        DRN1.setImage(UIImage(imageLiteralResourceName:"DRN1Logo"))
        DRN1.handler = { item, completion in
            print("selected DRN1")
            AdStichrApi.station = "DRN1"
            MusicPlayer.shared.startBackgroundMusic(url:"https://api.example.com.au:9000/station/DRN1", type: "radio")
            Nowplayinginfo().getsong()
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.00) {
                interfaceController.pushTemplate(nowplay, animated: true,completion:nil)
                completion()
            }
        }
        
        Hits.setImage(UIImage(imageLiteralResourceName:"DRN1Hits"))
        Hits.handler = { item, completion in
            print("selected Hits")
            MusicPlayer.shared.player?.pause()
            AdStichrApi.station = "DRN1Hits"
            MusicPlayer.shared.startBackgroundMusic(url:"https://api.example.com.au:9000/station/DRN1Hits", type: "radio")
            Nowplayinginfo().getsong()
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.00) {
               
                //interfaceController.presentTemplate(nowplay, animated: false)
                interfaceController.pushTemplate(nowplay, animated: true,completion:nil)
                completion()
                
            }
        }
        
        United.setImage(UIImage(imageLiteralResourceName:"DRN1United"))
        United.handler = { item, completion in
            print("selected United")
            AdStichrApi.station = "DRN1United"
            MusicPlayer.shared.startBackgroundMusic(url:"https://api.example.com.au:9000/station/DRN1United", type: "radio")
              // do work in the UI thread here
            Nowplayinginfo().getsong()
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.00) {
                interfaceController.pushTemplate(nowplay, animated: true,completion:nil)
                completion()
            }
            
            
            
        }
        
        Dance.setImage(UIImage(imageLiteralResourceName:"DRN1Dance"))
        Dance.handler = { item, completion in
            print("selected Dance")
            AdStichrApi.station = "dance"
            MusicPlayer.shared.startBackgroundMusic(url:"https://api.example.com.au:9000/station/dance", type: "radio")
            Nowplayinginfo().getsong()
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.00) {
                completion()
                interfaceController.pushTemplate(nowplay, animated: true,completion:nil)
            }
        }
        
        
        
        
    } else {
        // Fallback on earlier versions
    }
    
    
    
    let listTemplate = CPListTemplate(title: "Select a Station", sections: [CPListSection(items:[DRN1,United,Hits,Dance])])
   
   

但是在我的 iOS 应用程序中,我只使用

Api().getStations { (stations) in
                       self.stations = stations
        }

从后端获取 JSON 并为我提供每个可用的电台。

我想知道如何使用此信息创建 CPList。

示例: 我找到了这个例子,但它正在获取本地数据,此时我不需要标签栏。

https://github.com/T0yBoy/CarPlayTutorial/tree/master/CarPlayTutorial

根据我的理解,我需要做的就是创建一个列表

for station in (radios) {
            let item = CPListItem(text: station.name, detailText: station.name)
            item.accessoryType = .disclosureIndicator
            item.setImage(UIImage(named: station.imageurl))
            item.handler = { [weak self] item, completion in
                guard let strongSelf = self else { return }
               // strongSelf.favoriteAlert(radio: radio, completion: completion)
            }
            radioItems.append(item)
        
        }

我知道我需要按照

做一些事情

        Api().getStations { (stations) in
            self.radios = stations
            
            INSERT THE STATIONS INTO A LIST for 

let listTemplate = CPListTemplate(title: "Select a Station", sections: [CPListSection(items:stations)])
        }

这是从 API 创建列表后的样子

试一试:

// In some function in the CarPlaySceneDelegate
Api().getStations { (stations) in
    
    var stationItems: [CPListItem] = []
    
    self.radios = stations
    
    for station in stations {
        
        let item = CPListItem(text: station.name, 
                              detailText: station.description
                              image: station.image)
        
        item.handler = { [weak self] item, completion in
            
            // manage what should happen on tap
            // like navigate to NowPlayingView
            
        }
        
        stationItems.append(item)
    }
    
    loadList(withStations: stationItems)
}

// Load the list template
private func loadList(withStations stations: [CPListItem]) {
    
    let section = CPListSection(items: stations)
    let listTemplate = CPListTemplate(title: "Select a station",
                                      sections: [section])
    
    // Set the root template of the CarPlay interface
    // to the list template with a completion handler
    interfaceController?.setRootTemplate(listTemplate,
                                         animated: true) { success, error in
        
        // add anything you want after setting the root template
    }
}

CPListItem 数组中添加站点的 for 循环可以替换为 map 函数,但为了清楚起见,我这样做了。

更新

在您的 class CarPlaySceneDelegate 中,修正来自

的拼写
var interfactController: CPInterfaceController?

var interfaceController: CPInterfaceController?

在你的 templateApplicationScene didConnect 中暂时注释掉 interfactController?.setRootTemplate(listTemplate, animated: false)

并添加这一行 self.interfaceController = interfaceController

因此更新后的函数如下所示:

func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
                              didConnect interfaceController: CPInterfaceController) {
    
    // Add this
    self.interfaceController = interfaceController
    
    Api().getStations { (stations) in
        
        var stationItems: [CPListItem] = []
        
        self.stations = stations
        
        for station in stations {
            
            let item = CPListItem(text: station.name,
                                  detailText: station.name
                                  // image: imageLiteralResourceName:"DRN1Logo")
            )
            
            item.handler = { [weak self] item, completion in
                
                // manage what should happen on tap
                // like navigate to NowPlayingView
                print(item)
            }
            
            stationItems.append(item)
        }
        
        self.loadList(withStations: stationItems)
    }
}

你看到更好的结果了吗?