Bambelal
Bambelal

Reputation: 179

AVPlayer sometimes doesn't load a video

I have a one button and AVPlayer. After button click I record a video using DBAttachmentPickerController and I want to load it to the AVPlayer.

In function below I try to load it:

func refresh(attachmentInfo: AttachmentInfo) {
        self.videoLayer.player = nil
        if let url = attachmentInfo.url {
                self.player = AVPlayer(url: url) // line A
                self.videoLayer.player = self.player // line B
        }
}

In 6/10 cases it works fine, but sometimes the video doesn't load to AVPlayer.

When I set breakpoints in line A and B it works always.

Any ideas?

Upvotes: 1

Views: 1829

Answers (1)

Anjan Biswas
Anjan Biswas

Reputation: 7912

I also hit this exact issue as yours. In my case the AVPlayer and AVPlayerLayer were inside tableview cells which made the problem worse. However, I was using an API which returned the actual video URL, and an Image URL which consisted of the video's first frame's image. In the tableview cell logic, I first attempt to load the video into AVPlayer and then check if the AVPlayer has any .video assets, if it didn't then I simply load the Image from the other URL into the UIView (using a UIImageView of course) with a "Play" button image in the center of the Image. When the user taps the play button the selector function should try to load the AVPlayer again with the video URL. If the video loads and AVPlayer has assets then play() else simply return (and possibly alert the user that the video can't be loaded).

If you do not have the image of the first frame of the video, you can simply use a placeholder image and a button.

The way to check if the player has a video or not-

if player.currentItem?.asset.tracks(withMediaType: .video).count == 0{
   print("Oops! no video here")
   //load an image, and add a button here
}else{
   //do whatever needs to be done if video is available
}

Unfortunately, there isn't much else that can be done here unless you have some solid networking code where in you can download the video in a utility thread and store it in cache, but then again you have to be cognizant about the user's data usage, spawning too many download threads etc.

For image caching in the UITableView cell, I used SDWebImage library from Github so that I can be (somewhat) assured that my image (for the video) atleast would be cached in case of bad/slow network, or network interruptions.

Upvotes: 1

Related Questions