I am making an iOS app that can be compared to instagram with a feed of videos (no images). I have a table showing custom table view cells, each table view cell contains a video playing using AVKit. I have 6 cells loading at the moment, and it is using an unbelievable amount of memory to show them. How does an app like facebook, instagram, or vine show that many videos without using an insane amount of memory?
Below is the code that I am currently using.
var cells: [VideoCell] = []
var cellPostkeys: [String] = []
@IBOutlet weak var feedTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
feedTableView.delegate = self
feedTableView.dataSource = self
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoURLs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let url = videoURLs[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "testcell") as? VideoCell {
if (cellPostkeys.contains(url)) {
let index = cellPostkeys.firstIndex(of: url)
cells[index!] = cell
} else {
cells.append(cell)
cellPostkeys.append(url)
}
cell.playvid(url: url)
return cell
} else {
return VideoCell()
}
}
}
And this is the code for my custom table view cell
class VideoCell: UITableViewCell {
@IBOutlet weak var videoView: UIView!
var player : AVPlayer!
var avPlayerLayer : AVPlayerLayer!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
//
}
func stopvid() {
self.player = nil
self.avPlayerLayer = nil
}
func playvid(url: String) {
self.player = AVPlayer(url: URL(string: url)!)
self.avPlayerLayer = AVPlayerLayer(player: self.player)
self.avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.player.automaticallyWaitsToMinimizeStalling = false
avPlayerLayer.frame = videoView.layer.bounds;
self.videoView.layer.addSublayer(self.avPlayerLayer)
self.player.play()
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { [weak self] _ in
self?.player?.seek(to: CMTime.zero)
self?.player?.play()
}
}
}
I understand that loading and playing 6 videos at once is obviously going to be incredibly memory taxing, so I tried only playing 1 video and the other 5 cells being empty, but that was also using about 100+ mb of memory once I started scrolling up and down. Any and all help would be greatly appreciated.