-1

I have a view controller which I made through coding rather than storyboard to display a video. once the video has finished playing I cannot get the view controller to return to the previous one. I have a button which takes the user to the video but when the video finish it doesn't go back to the previous view controller.

import AVKit
import AVFoundation
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "tour", ofType: "mov")!))


   let vc = AVPlayerViewController()
      vc.player = player
     present(vc, animated: true)
    }


}

this is my code for my video. I have done everything else to build the app on my storyboard

MMG
  • 3,226
  • 5
  • 16
  • 43

1 Answers1

0

To go back to the previous VC after the video finishes, you need to -

  1. add an observer which could detect when the video stops playing and then -
  2. dismiss the AVPlayerViewController

To accomplish task 1 - this answer by Channel helps set up the observer -https://stackoverflow.com/a/40056529/13451699

To do task 2 - just dismiss the AVPlayerViewController from inside the playerDidFinishPlaying function, like so :

func playerDidFinishPlaying(note: NSNotification){
  // Video finished playing
  self.dismiss(animated: true, completion: nil)
}
Animesh K
  • 78
  • 6
  • I am new to coding. could you please explain to me how I will do task 2, how will I add the observer to my swift code. also to dismiss AVPlayerViewController should I just delete that section. thank you – Joshua Samson May 04 '20 at 21:50
  • I've edited the answer to illustrate how you could accomplish task 2 – Animesh K May 05 '20 at 12:17
  • Happy to help.. If the answer helped, please accept it :) – Animesh K May 06 '20 at 03:07