3
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!

LYM
  • 251
  • 3
  • 9
  • Does https://stackoverflow.com/a/40088125/22147 answer your question? – Rhythmic Fistman May 27 '17 at 00:04
  • This code looks fine, but it must be run on the device, and it only works for HLS assets, e.g. this one: http://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8 (requires App Transport Security to be disabled) – Rhythmic Fistman May 27 '17 at 01:55
  • @RhythmicFistman Thank you. HLS asset seems to be the point. I try your url and the first method is called, but the second method about download progress is still not called. – LYM May 27 '17 at 06:24
  • Possible duplicate of [AVAssetDownloadDelegate methods for HLS caching not getting called](https://stackoverflow.com/questions/40084347/avassetdownloaddelegate-methods-for-hls-caching-not-getting-called) – Cœur Jul 26 '19 at 10:13

0 Answers0