如何获取当前曲目并在CPNowPlayingTemplate中配置显示曲目信息?
给CPNowPlayingTemplate配置曲目信息的方法
要让CPNowPlayingTemplate正确显示曲目信息,核心是通过MPNowPlayingInfoCenter传递数据,同时配合播放逻辑调整,以下是具体修改和说明:
1. 正确填充MPNowPlayingInfoCenter的曲目数据
CPNowPlayingTemplate会自动读取MPNowPlayingInfoCenter.default().nowPlayingInfo中的数据,你需要把硬编码的测试值替换为真实播客数据,还可补充更多字段让界面更完整:
var nowPlayingInfo = [String: Any]() // 替换为真实的播客标题和作者 nowPlayingInfo[MPMediaItemPropertyTitle] = podcast.name nowPlayingInfo[MPMediaItemPropertyArtist] = podcast.author // 假设你的podcast模型有author字段 // 可选:添加时长信息(如果有) if let duration = podcast.duration { nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration } // 可选:添加专辑封面(需要转换为MPMediaItemArtwork) if let imageURL = podcast.imageURL, let imageData = try? Data(contentsOf: imageURL), let image = UIImage(data: imageData) { nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in return image } } MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
2. 调整播放逻辑与模板推送的顺序
建议先设置好曲目信息、准备好播放队列,再推送CPNowPlayingTemplate,避免界面加载时信息为空:
itemLista.handler = { [weak self] item, completion in guard let this = self else { return } // 1. 先设置曲目信息 var nowPlayingInfo = [String: Any]() nowPlayingInfo[MPMediaItemPropertyTitle] = podcast.name nowPlayingInfo[MPMediaItemPropertyArtist] = podcast.author MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo // 2. 准备播放队列并开始播放 this.playWithItems(items: [podcast.identifier!]) // 3. 推送NowPlaying模板 let nowPlayingTemplate = CPNowPlayingTemplate.shared this.interfaceController?.pushTemplate(nowPlayingTemplate, animated: true, completion: nil) completion() }
3. CPNowPlayingTemplate的额外注意事项
CPNowPlayingTemplate.shared是单例,无需重复调用add(this),直接使用即可- 如果需要自定义NowPlaying界面布局,可以创建自定义的
CPNowPlayingTemplate子类,或通过nowPlayingTemplate.controls添加自定义控件,默认模板已自动展示MPNowPlayingInfoCenter中的核心信息
修改后的完整代码示例
itemLista = CPListItem(text: podcast.name, detailText: podcast.date) itemLista.handler = { [weak self] item, completion in guard let this = self else { return } // 填充真实的曲目信息 var nowPlayingInfo = [String: Any]() nowPlayingInfo[MPMediaItemPropertyTitle] = podcast.name nowPlayingInfo[MPMediaItemPropertyArtist] = podcast.author ?? "未知作者" if let duration = podcast.duration { nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration } MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo // 启动播放 this.playWithItems(items: [podcast.identifier!]) // 推送NowPlaying模板 let nowPlayingTemplate = CPNowPlayingTemplate.shared this.interfaceController?.pushTemplate(nowPlayingTemplate, animated: true, completion: nil) completion() } func playWithItems(items: [String]) { let player = MPMusicPlayerController.applicationQueuePlayer player.pause() player.setQueue(with: items) player.prepareToPlay() player.play() }
内容的提问来源于stack exchange,提问作者user20459409
相关产品推荐
相关产品推荐

