class StreamPlayer: NSObject {
fileprivate let sessionID = "StreamPlayerAssetDownloadURLSession"
var remoteURL: URL
var session: AVAssetDownloadURLSession!
var task: AVAssetDownloadTask?
var asset: AVURLAsset?
var player: AVPlayer?
var layer: AVPlayerLayer {
return AVPlayerLayer(player: player)
}
weak var delegate: StreamPlayerDelegate?
init(remoteURL: URL) {
self.remoteURL = remoteURL
super.init()
let config = URLSessionConfiguration.background(withIdentifier: sessionID)
session = AVAssetDownloadURLSession(configuration: config, assetDownloadDelegate: self, delegateQueue: .main)
}
func prepareToPlay() {
asset = AVURLAsset(url: remoteURL)
task = session.makeAssetDownloadTask(asset: asset!, assetTitle: "", assetArtworkData: nil, options: nil)
task!.resume()
let playerItem = AVPlayerItem(asset: task!.urlAsset)
player = AVPlayer(playerItem: playerItem)
}
func play() {
player?.play()
}
}
extension StreamPlayer: AVAssetDownloadDelegate {
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
print(location)
}
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didLoad timeRange: CMTimeRange, totalTimeRangesLoaded loadedTimeRanges: [NSValue], timeRangeExpectedToLoad: CMTimeRange) {
print(timeRange)
}
}
I read apple's guide, and write the code. The function is very simple, to play and download video at the same time. I initialize the player, call prepareToPlay() and play() methods, and add the player layer to a view, then the video play well as expected. But the two delegate's methods never called, so I can't save the video URL or display the progress of caches. Someone said it's because of running on simulator, but I've tried on either simulator or real devices, and the result is the same. BTW, I've tried "mp4" and "m3u8" format, both are playable but the neither delegate's method is called. Someone can please tell me is there something I missed? Thanks a lot!