Reputation: 816
I have a tableview where I am trying to load videos and play them on viewdidLoad()
Following is the code for load video on Viewdidload
func playVideo(viewController:UIViewController,videoPath:String!, view: UIView) {
guard let path = videoPath else {
debugPrint("video.m4v not found")
return
}
let url = NSURL.fileURL(withPath: path)
let item = AVPlayerItem(url: url)
self.player = AVPlayer(playerItem: item)
self.videoPlayerController = AVPlayerViewController()
self.videoPlayerController.player = self.player
videoPlayerController.view.frame = view.bounds
viewController.addChildViewController(videoPlayerController)
view.addSubview(videoPlayerController.view)
}}
Inside cellForRowAtIndexPath I'm doing the following
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
cell = tableView.dequeueReusableCell(withIdentifier: "trendViewControllerCell", for: indexPath) as! TrendViewTableCell
cell.videoName.text = feeds[indexPath.row].videoTitle
cell.artistName.text = feeds[indexPath.row].artistName
player.playVideo(viewController: self, videoPath: Bundle.main.path(forResource: feeds[indexPath.row].videoUrl, ofType:"mp4")!, view: cell.videoView)
return cell
}
I am trying to resize the AVPlayerController to the view in tableView cell.
On viewDidLoad I am able to see an AVPlayer controller for all views in the cells.
There are about 15 videos
As I scroll down further I see a cancelled buttons and none of the videos load. Sometimes all the videos load and sometimes they don't.
However I don't see this problem in the simulator.
How can I solve this problem? Any help will be appreciated
Upvotes: 2
Views: 1290
Reputation: 4906
Sorry but your approach is not a good idea: have a single AVPlayer for every cell is very heavy and you can encounter lots of problems related like reload the video every time your cell appears, jerky scrolling, bad performance, etc.
In addition keep in mind that AVPlayer is instantiated always in the main thread, so while scrolling you shouldn't instantiate any other player video otherwise you keep busy the main thread (the same thread that does UI updates!).
Like Instagram and Facebook do the common approach here is have a common instance of an AVPlayer video and images of the first or last frame for every video: when your cell is completely visibile put over the image your video player view passing the video url using replaceCurrentItemWithPlayerItem
.
It's not an easy and quick thing to do so take your time and be patience, with time you will build your solution; you can find more info on these questions:
Upvotes: 2