1

When the cell is tapped if there is a video, I want to show only the video (in a avPlayerViewController), if there is no video it performs a segue to a detail vieww

I have tried this:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


    let post = postArray[indexPath.item]
    let controller = PostDetailViewController.fromStoryboard(post: post)
    self.navigationController?.pushViewController(controller, animated: true)


    guard let videoURL = URL(string: post.videoLink)  else {
        return
            }

    let avPlayer = AVPlayer(url: videoURL)
    let avController = AVPlayerViewController()
    avController.player = avPlayer

    present(avController, animated: true) {
        avPlayer.play()
    }

}

It plays the video if there is one (from Firebase), but it also opens the detail view. So I wanted the cell to open only the video or only the detailview

H. Osjir
  • 145
  • 2
  • 7

1 Answers1

1

Structure it so that, if there is no post.videoLink then it pushes the PostDetailViewController, otherwise it will play the video:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    guard let videoURL = URL(string: post.videoLink) else {
        //If there is no URL, then this else condition will be called. Otherwise, the code below the guard statement will be called, and the video player will appear.
        let post = postArray[indexPath.item]
        let controller = PostDetailViewController.fromStoryboard(post: post)
        self.navigationController?.pushViewController(controller, animated: true)
        return
    }

    let avPlayer = AVPlayer(url: videoURL)
    let avController = AVPlayerViewController()
    avController.player = avPlayer

    present(avController, animated: true) {
        avPlayer.play()
    }

}
David Chopin
  • 2,780
  • 2
  • 19
  • 40
  • I tried something like this `if post.videoLink == ""`, but it didn't work. How can I do that? – H. Osjir Oct 19 '19 at 15:05
  • Well, when a post doesn’t have a video associated with it, is `post.videoLink` equal to `””` or is it equal to `nil`? – David Chopin Oct 19 '19 at 15:29
  • When I make it equal to nil, i get `'nil' cannot be assigned to type 'String'`. I'm a bit new to swift, so I dont know what to do. – H. Osjir Oct 19 '19 at 15:45
  • Can you check what the value of `post.videoLink` is in a post without a video? I imagine it is equal to `””`. It cannot be equal to `nil`. – David Chopin Oct 19 '19 at 15:46
  • The videoLink is `””`when it is in a post without a video – H. Osjir Oct 19 '19 at 15:50
  • 1
    Thank you for your help, it worked when I put `pushViewController(controller, animated: true)` in `if post.videoLink == ""` – H. Osjir Oct 19 '19 at 16:07