Güney Güney - 1 year ago 69
Swift Question

Why does Swift's AVPlayer loads the playerItem for twice on one play?

I'm using AVFoundation's AVPlayer for streaming external mp3 files. I have a counter on the back-end that counts how many times a file loaded. The only client for this service is only me and whenever I trigger to play the AVPlayer, the counter increases two which means AVPlayer makes the request twice. Is there a reason for this, or how can I prevent that from happening? Here is my code:

@IBAction func listen(sender: UIButton) {
let urlstring = "http://api.server.com/endpoint-to-mp3"
let url = NSURL(string: urlstring)

let playerItem = AVPlayerItem(URL: url!)

let player = AVPlayer(playerItem: playerItem)

let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = CGRectMake(0, 0, 300, 50)

player.volume = 1.0

Answer Source

Not exactly. AVPlayer is making a network request to the URL whenever you initialize the player with AVPlayerItem. This call only fetches the file information and file size. (At this point I am able to observe 2 requests sometime, which could increase your count to 3)

Later when you are attaching the player to any view, another call is happening to fetch the complete file. (You can use Charles to observe your network traffic, fyi)

This behaviour is same when you init the player with init(url:) So I don't see any way that could prevent this from happening at the moment.

enter image description here