Shawn Chen
Shawn Chen

Reputation: 5

Ios Swift 3 automatically playing a video after the page loads

Im currently using 'AVKit' and 'AVFoundation' to enable the video playing through my app but I can only done by starting the video by tapping a button. But I am currently facing a problem of trying to making an automatic function like playing the video footage right after we start an app on an iOS device.

override func viewDidLoad() 
{ 
  super.viewDidLoad()
  self.playingVideo()
  self.nowPlaying(self)
}

@IBAction func nowPlaying(_ sender: Any) 
{
  self.present(self.playerController, animated: true, completion:{
  self.playerController.player?.play()                
})

after I compiled it, the system printed out:

Warning: Attempt to present on whose view is not in the window hierarchy!

Upvotes: 0

Views: 2644

Answers (1)

Devanshu Saini
Devanshu Saini

Reputation: 775

Please try following working code.

import AVFoundation
import UIKit

class SomeViewController: UIViewController {

    func openVideo() {
        let playerController = SomeMediaPlayer()
        playerController.audioURL = URL(string: "Some audio/video url string")
        self.present(playerController, animated: true, completion: nil)
    }
}

class SomeMediaPlayer: UIViewController {
    public var audioURL:URL!
    private var player = AVPlayer()
    private var playerLayer: AVPlayerLayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.playerLayer = AVPlayerLayer(player: self.player)
        self.view.layer.insertSublayer(self.playerLayer, at: 0)
        let playerItem = AVPlayerItem(url: self.audioURL)
        self.player.replaceCurrentItem(with: playerItem)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.player.play()
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.playerLayer.frame = self.view.bounds
    }

    // Force the view into landscape mode if you need to
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return .landscape
        }
    }
}

Upvotes: 1

Related Questions