Codifydxt
Codifydxt

Reputation: 11

How to play videos from url in Avplayer when a cell is tapped using swift 3

I m trying to play videos from url in UITableViewCell with AVPlayer. I mean I want videos to play when a VideoTableviewCell which has an image for videos introduction and Label:title for that videos. When that image of video tapped on cell then that video from url will play in Avplayer controller. My problem is i am not able to get which cell image is tapped and how to play corresponding video url in another ViewController(AVplayerViewController). Can anyone help me to understand what to use to recognize and connect which image is tapped and how to play video in another viewcontroller.

Upvotes: 0

Views: 1555

Answers (2)

Ridho Octanio
Ridho Octanio

Reputation: 553

In Swift 4.2

You need to implement didSelectRowAt and AVKit

First you need to import AV Kit

import AVKit

Next, get url from index cell in didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   if let url = URL(string: yourArrayURL[indexPath.row]) {
      let player = AVPlayer(url: url)
      let playerViewController = AVPlayerViewController()
      playerViewController.player = player
      present(playerViewController, animated: true) {
         player.play()
      }
   }
}

In my case it's work, I hope it's work for you too

Upvotes: 2

Sean Lintern
Sean Lintern

Reputation: 3141

Implement

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

then inside this:

    if let cell = tableView.cellForRow(at: indexPath) as? VideoTableviewCell {
        // cell.AVplayer.play
    }

This is a built in UITableView method to tell you when an individual cell is tapped.

Upvotes: 1

Related Questions