我为此苦苦挣扎了一段时间。如果这曾经是一个实际的错误,我不确定,但是您不能按照您期望的方式UIImageView
设置a 。nowPlayingItem
您必须从 Apple Music 服务 api 中提取图像。请参阅此处的文档。还可以查看 Apple 提供的示例项目,以便全面了解。另外这里是我如何克服这个问题的完整示例。
func updateUserInterface() {
if musicPlayerManager.musicPlayerController.playbackState == .playing { //Check if anything is playing
if let currentItem = musicPlayerManager.musicPlayerController.nowPlayingItem {
songAlbumLabel.text = currentItem.albumTitle
songTitleLabel.text = currentItem.title
songArtistNameLabel.text = currentItem.artist
let albumTitle = currentItem.albumTitle //Changes here!
let artist = currentItem.artist //Changes here!
if let artwork = musicPlayerManager.musicPlayerController.nowPlayingItem?.artwork, let image = artwork.image(at: artworkImageView.frame.size) { // Check for local image
print("using local image")
artworkImageView.image = image
} else {
guard let developerToken = appleMusicManager.fetchDeveloperToken() else {print("oops");return}
let searchTypes = "songs"
var searchURLComponents = URLComponents()
searchURLComponents.scheme = "https"
searchURLComponents.host = "api.music.apple.com"
searchURLComponents.path = "/v1/catalog/"
searchURLComponents.path += "\(authorizationManager.cloudServiceStoreFrontCountryCode)"
searchURLComponents.path += "/search"
let expectedArtist = artist?.replacingOccurrences(of: " ", with: "+") //Changes here!
let artistExpected = expectedArtist?.replacingOccurrences(of: "&", with: "") //Changes here!
let expectingArtist = artistExpected?.replacingOccurrences(of: "++", with: "+") //Changes here!
let expectedAlbum = albumTitle?.replacingOccurrences(of: " ", with: "+") //Changes here!
searchURLComponents.queryItems = [
URLQueryItem(name: "term", value: (expectingArtist! + "-" + expectedAlbum!)),
URLQueryItem(name: "types", value: searchTypes)
] //Changes here!
var request = URLRequest(url: searchURLComponents.url!)
request.httpMethod = "GET"
request.addValue("Bearer \(developerToken)", forHTTPHeaderField: "Authorization")
let dataTask = URLSession.shared.dataTask(with: request) {
(data, response, error) in
print(response!)
if let searchData = data {
guard let results = try? self.appleMusicManager.processMediaItemSections(searchData) else { return}
self.mediaItem = results
let album = self.mediaItem[0][0]
let albumArtworkURL = album.artwork.imageUrl(self.artworkImageView.frame.size)
if let image = self.imageManager.cachedImage(url: albumArtworkURL) {
print("using cached image")
self.artworkImageView.image = image
}
else {
self.imageManager.fetchImage(url: albumArtworkURL) {(image) in
print("fetching image")
self.artworkImageView.image = image
}
}
}
}
dataTask.resume()
}
} else { // Need to set it to some kind of default values
artworkImageView.image = nil
songArtistNameLabel.text = " "
songTitleLabel.text = " "
songAlbumLabel.text = " "
}
}
}