4

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)
    self.view.layer.addSublayer(playerLayer)

    player.volume = 1.0
    player.play()
}
Guney Cobanoglu
  • 733
  • 1
  • 6
  • 20
  • Do you see what type of requests are made? Could one be a header-only request and another be for the actual data? –  May 16 '16 at 00:49

1 Answers1

7

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

Penkey Suresh
  • 5,816
  • 3
  • 36
  • 55