Play video in UITableViewCell or UICollectionViewCell iOS

Stackoverflow has a lot of material on how to play video in a cell, that everyone can feel embarrassed, especially since most of the issues are not resolved, and it seems that every developer refuses.

So, I wanted to create a new question, where the answers will be updated.

Purpose:

Play the video in a UITableViewCell or UICollectionViewCell when the user clicks on the cell (yes, this is a simplified version, this is not about autistic mode).

Decision:

  • I think everyone agrees on what we should use AVPlayerinstead of the obsolete one MPMoviePlayerController.
  • The cell must have a layer on which AVPlayer can be assigned, so in my code when creating the cell I added this code:

VideoCell.swift

let layer = AVPlayerLayer()
layer.backgroundColor = UIColor.clear.cgColor
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
  • , , :

ViewController.swift

cell.playerLayer.player = player
player.replaceCurrentItem(with: AVPlayerItem(asset: asset))
player.play()

AVPlayer, - AVAsset, URL- .

, AVPlayer , , . , , .

: , ? ? Facebook Instagram , , -, ?

Objective-C .

+4

Source: https://habr.com/ru/post/1672683/


All Articles