AVAssetDownloadDelegate methods not called in real devices

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 have read the apple guide and will write some code. The function is very simple to play and download videos at the same time. I initialize the player, call the prepareToPlay () and play () methods and add the player layer to the view, then the video plays as expected. But the two delegate methods were never called, so I can't save the video url or show the progress of the caches. Someone said this because of running a simulator, but I tried either the simulator or real devices and the result is the same. BTW, I've tried the "mp4" and "m3u8" format, both playable but neither delegate method is called. Can someone tell me I missed something? Many thanks!

+3


source to share





All Articles