Update artwork of AVPlayer using URLSession

This commit is contained in:
Arkadiusz Fal 2022-06-27 12:14:51 +02:00
parent bed7e759a8
commit f2c79a941e

View File

@ -287,7 +287,7 @@ final class AVPlayerBackend: PlayerBackend {
} }
addItemDidPlayToEndTimeObserver() addItemDidPlayToEndTimeObserver()
attachMetadata(to: model.playerItem!, video: video, for: stream) attachMetadata()
DispatchQueue.main.async { DispatchQueue.main.async {
self.stream = stream self.stream = stream
@ -386,27 +386,42 @@ final class AVPlayerBackend: PlayerBackend {
} }
} }
private func attachMetadata(to item: AVPlayerItem, video: Video, for _: Stream? = nil) { private func attachMetadata() {
guard let video = model.currentVideo else { return }
#if !os(macOS) #if !os(macOS)
var externalMetadata = [ var externalMetadata = [
makeMetadataItem(.commonIdentifierTitle, value: video.title), makeMetadataItem(.commonIdentifierTitle, value: video.title),
makeMetadataItem(.quickTimeMetadataGenre, value: video.genre ?? ""), makeMetadataItem(.quickTimeMetadataGenre, value: video.genre ?? ""),
makeMetadataItem(.commonIdentifierDescription, value: video.description ?? "") makeMetadataItem(.commonIdentifierDescription, value: video.description ?? "")
] ]
if let thumbnailData = try? Data(contentsOf: video.thumbnailURL(quality: .medium)!),
let image = UIImage(data: thumbnailData), if let thumbnailURL = video.thumbnailURL(quality: .medium) {
let pngData = image.pngData() let task = URLSession.shared.dataTask(with: thumbnailURL) { [weak self] thumbnailData, _, _ in
{ guard let thumbnailData = thumbnailData else { return }
let artworkItem = makeMetadataItem(.commonIdentifierArtwork, value: pngData)
externalMetadata.append(artworkItem) let image = UIImage(data: thumbnailData)
if let pngData = image?.pngData() {
if let artworkItem = self?.makeMetadataItem(.commonIdentifierArtwork, value: pngData) {
externalMetadata.append(artworkItem)
}
}
self?.avPlayer.currentItem?.externalMetadata = externalMetadata
}
task.resume()
} }
item.externalMetadata = externalMetadata
#endif #endif
item.preferredForwardBufferDuration = 5 if let item = model.playerItem {
#if !os(macOS)
observePlayerItemStatus(item) item.externalMetadata = externalMetadata
#endif
item.preferredForwardBufferDuration = 5
observePlayerItemStatus(item)
}
} }
#if !os(macOS) #if !os(macOS)