AVPlayer video still playing after segue to next view controller - ios

I'm currently looping my mp4 video with no playback controls, kind of like a gif but with sound. But I do not know why when I segue to the next view controller, the video is still playing. Does anybody know the simplest method to resolve this issue?
ViewController
import UIKit
import AVKit
import AVFoundation
fileprivate var playerObserver: Any?
class ScoreController: UIViewController {
#IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let returnValue: Int = UserDefaults.standard.integer(forKey: "userScore")
label.text = "Your Score: \(returnValue)/30"
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
let path = Bundle.main.path(forResource: "Innie-Kiss", ofType:"mp4")
let player = AVPlayer(url: URL(fileURLWithPath: path!))
let resetPlayer = {
player.seek(to: kCMTimeZero)
player.play()
}
playerObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: nil) { notification in resetPlayer() }
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = false
self.addChildViewController(controller)
let screenSize = UIScreen.main.bounds.size
let videoFrame = CGRect(x: 0, y: 130, width: screenSize.width, height: (screenSize.height - 130) / 2)
controller.view.frame = videoFrame
self.view.addSubview(controller.view)
player.play()
} catch {
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
fileprivate var player: AVPlayer? {
didSet { player?.play() }
}
deinit {
guard let observer = playerObserver else { return }
NotificationCenter.default.removeObserver(observer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func doneButton(_ sender: Any) {
self.performSegue(withIdentifier: "done", sender: self)
}
}

In viewWillDisapper() or button action for segue do this :
NotificationCenter.default.removeObserver(self)
Also move this from viewDidLoad() to some function like :
var player: AVPlayer?
func audioPlayer(){
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
let path = Bundle.main.path(forResource: "Innie-Kiss", ofType:"mp4")
player = AVPlayer(url: URL(fileURLWithPath: path!))
let resetPlayer = {
self.player?.seek(to: kCMTimeZero)
self.player?.play()
}
playerObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: nil) { notification in resetPlayer() }
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = false
self.addChildViewController(controller)
let screenSize = UIScreen.main.bounds.size
let videoFrame = CGRect(x: 0, y: 130, width: screenSize.width, height: (screenSize.height - 130) / 2)
controller.view.frame = videoFrame
self.view.addSubview(controller.view)
player?.play()
} catch {
}
}
and make player object a global variable. var player = AVPlayer? and in viewWillDisappear make it nil.
So your viewWillDisappear should look like this :
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
if player != nil{
player?.replaceCurrentItem(with: nil)
player = nil
}
}

override func viewWillDisappear(_ animated: Bool) {
}
This may be helpful to you if you are switching windows; as you perform a segue, you will execute the function included in curly brackets automatically. I'm rubbish with AV, but some of the other's code suggested to turn off the function may work here if it isn't working in the IBAction.
I'm not great with Xcode though, so mileage will probably vary.

I had this issue and fixed it by adding this line before setting player to nil:
[self.player pause];
here is my viewWillDisapear:
- (void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:AVPlayerItemDidPlayToEndTimeNotification
object:self.player];
[self.player removeObserver:self forKeyPath:#"rate"];
[self.player removeTimeObserver:self.playerObserver];
self.playerObserver = nil;
[self.player pause];
self.player = nil;
[[UIDevice currentDevice] setValue:#(UIInterfaceOrientationPortrait) forKey:#"orientation"];
[UINavigationController attemptRotationToDeviceOrientation];
[StayfilmApp restrictOrientation:YES];
}

class ScoreController: UIViewController {
#IBOutlet var label: UILabel!
var player: AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let returnValue: Int = UserDefaults.standard.integer(forKey: "userScore")
label.text = "Your Score: \(returnValue)/30"
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
let path = Bundle.main.path(forResource: "Innie-Kiss", ofType:"mp4")
player = AVPlayer(url: URL(fileURLWithPath: path!))
let resetPlayer = {
player.seek(to: kCMTimeZero)
player.play()
}
playerObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: nil) { notification in resetPlayer() }
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = false
self.addChildViewController(controller)
let screenSize = UIScreen.main.bounds.size
let videoFrame = CGRect(x: 0, y: 130, width: screenSize.width, height: (screenSize.height - 130) / 2)
controller.view.frame = videoFrame
self.view.addSubview(controller.view)
player.play()
} catch {
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
player.pause()
}
fileprivate var player: AVPlayer? {
didSet { player?.play() }
}
deinit {
guard let observer = playerObserver else { return }
NotificationCenter.default.removeObserver(observer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func doneButton(_ sender: Any) {
self.performSegue(withIdentifier: "done", sender: self)
}
}
notable changes:
var player: AVPlayer?
and also
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
player?.pause()
}

I have the same problem when I used segue to go to the next ViewController, then I used present code with swift by using this code
#IBAction func next(_ sender: Any) {
let vc = self .storyboard?.instantiateViewController(withIdentifier:"ViewControllerAA") as! ViewControllerAA
self.present(vc,animated: true,completion: nil)
}
but the problem didn't solve , then I used this code to go to the next VC and my problem solved and the background sound of the video stoped, and the code is this below
#IBAction func next(_ sender: Any) {
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerAA") as? ViewControllerAA {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = vc
}
}

Related

IOS 14 AVPlayer plays on simulator but doesn't on a real device

I have splash screen as a short mov video for my application and I use AVPlayer (code below) for that. It stopped working with the IOS 14 physical device, while on the simulator it works fine. Could you help with that?
import UIKit
import AVKit
import AVFoundation
class PlayerVC: UIViewController, AVAudioPlayerDelegate {
lazy var player: AVPlayer = {
let fileName = "test"
let path = Bundle.main.path(forResource: fileName, ofType: "mov")!
let videoURL = URL(fileURLWithPath: path)
let player = AVPlayer(url: videoURL)
return player
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewTapped)))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.shouldRasterize = true
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
}
#objc func playerDidFinishPlaying(sender: NSNotification) {
loadRootVC()
}
private func loadRootVC() {
dismiss(animated: false, completion: nil)
self.onVideoFinished();
}
#objc func viewTapped() {
loadRootVC()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}

Adding a looped mp4 Background to iOS app signup

I want to end up applying this code to make my app look a little nicer when users are logging into their social media accounts. I've tried the following code already but my app seems to crash as soon as the mp4 ends.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
let theURL = Bundle.main.url(forResource: "Yeet", withExtension: "mp4")
avPlayer = AVPlayer(url: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = UIColor.clear;
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self, selector: Selector(("playerItemDidReachEnd:")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem)
}
#objc func playerItemDidReachEnd(notification: NSNotification) {
let p: AVPlayerItem = notification.object as! AVPlayerItem
p.seek(to: CMTime.zero)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidDisappear(animated)
avPlayer.play()
paused = false
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
avPlayer.pause()
paused = true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
Have you tried using AVPlayerLooper?
Looks like #iwasrobbed has a solution for iOS 10+ devices. Here's the example code:
private var looper: AVPlayerLooper?
...
let queuePlayer = AVQueuePlayer(playerItem: item)
looper = AVPlayerLooper(player: queuePlayer, templateItem: item)
videoPlayerLayer.player = queuePlayer
To disable the loop after leaving the view, add this piece of code in the end:
looper?.disableLooping()

Swift 4 & Xcode 10. Play video on app launch, when complete, reveal view controller

Firstly, I'm totally new to Xcode 10 and Swift 4, and I've searched here but haven't found code that works.
What I'm after:
On launching app to play a video which is stored locally (called "launchvideo").
On completion of video to display/move to a UIviewcontroller with a storyboard ID of "menu"
So far I have my main navigation controller with it's linked view controller.
I'm guessing I need a UIview to hold the video to be played in on this page?
Is there someone who can help a new guy out?
Thanks
Firstly change your launch screen storyboard to Main storyboard from project settings in General tab.
Create one view controller with following name and write code to implement AVPlayer to play video.
import UIKit
import AVFoundation
class VideoLaunchVC: UIViewController {
func setupAVPlayer() {
let videoURL = Bundle.main.url(forResource: "Video", withExtension: "mov") // Get video url
let avAssets = AVAsset(url: videoURL!) // Create assets to get duration of video.
let avPlayer = AVPlayer(url: videoURL!) // Create avPlayer instance
let avPlayerLayer = AVPlayerLayer(player: avPlayer) // Create avPlayerLayer instance
avPlayerLayer.frame = self.view.bounds // Set bounds of avPlayerLayer
self.view.layer.addSublayer(avPlayerLayer) // Add avPlayerLayer to view's layer.
avPlayer.play() // Play video
// Add observer for every second to check video completed or not,
// If video play is completed then redirect to desire view controller.
avPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1) , queue: .main) { [weak self] time in
if time == avAssets.duration {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") as! ViewController
self?.navigationController?.pushViewController(vc, animated: true)
}
}
}
//------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
}
//------------------------------------------------------------------------------
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.setupAVPlayer() // Call method to setup AVPlayer & AVPlayerLayer to play video
}
}
Main.Storyboard:
Project Launch Screen File:
See following video also:
https://youtu.be/dvi0JKEpNTc
You have to load a video on launchvideoVC, like below way in swift 4 and above
import AVFoundation
import AVKit
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
initVideo()
}
func initVideo(){
do {
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error)
}
let path = Bundle.main.path(forResource: "yourlocalvideo", ofType:"mp4");
player = AVPlayer(url: NSURL(fileURLWithPath: path!) as URL)
NotificationCenter.default.addObserver(self, selector: #selector(launchvideoVC.itemDidFinishPlaying(_:)), name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
DispatchQueue.main.async(execute: {() -> Void in
let playerLayer = AVPlayerLayer(player: self.player)
playerLayer.frame = self.view.bounds
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer.zPosition = 1
self.view.layer.addSublayer(playerLayer)
self.player?.seek(to: CMTime.zero)
self.player?.play()
})
}
#objc func itemDidFinishPlaying(_ notification: Notification?) {
//move to whatever UIViewcontroller with a storyboard ID of "menu"
}
I think it's may help you.
Happy coding :)
First you make a new view controller with view and change your launch screen storyboard to Main storyboard from project settings in General tab.
And also add your video in folder.
Then just add my below code to your launch screenView controller:
import UIKit
import MediaPlayer
import AVKit
class LaunchViewController: UIViewController {
fileprivate var rootViewController: UIViewController? = nil
var player: AVPlayer?
var playerController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
showSplashViewController()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func playVideo() {
let videoURL = NSURL(string: "videoplayback")
player = AVPlayer(url: videoURL! as URL)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
// Add your view Frame
playerController.view.frame = self.view.frame
// Add subview in your view
self.view.addSubview(playerController.view)
player?.play()
}
private func loadVideo() {
//this line is important to prevent background music stop
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
} catch { }
let path = Bundle.main.path(forResource: "videoplayback", ofType:"mp4")
let filePathURL = NSURL.fileURL(withPath: path!)
let player = AVPlayer(url: filePathURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer.zPosition = -1
self.view.layer.addSublayer(playerLayer)
player.seek(to: kCMTimeZero)
player.play()
}
func showSplashViewControllerNoPing() {
if rootViewController is LaunchViewController {
return
}
loadVideo()
}
/// Simulates an API handshake success and transitions to MapViewController
func showSplashViewController() {
showSplashViewControllerNoPing()
delay(6.00) {
self.showMenuNavigationViewController()
}
}
public func delay(_ delay:Double, closure:#escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
/// Displays the MapViewController
func showMenuNavigationViewController() {
guard !(rootViewController is Home) else { return }
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nav = storyboard.instantiateViewController(withIdentifier: "homeTab") as! Home
nav.willMove(toParentViewController: self)
addChildViewController(nav)
if let rootViewController = self.rootViewController {
self.rootViewController = nav
rootViewController.willMove(toParentViewController: nil)
transition(from: rootViewController, to: nav, duration: 0.55, options: [.transitionCrossDissolve, .curveEaseOut], animations: { () -> Void in
}, completion: { _ in
nav.didMove(toParentViewController: self)
rootViewController.removeFromParentViewController()
rootViewController.didMove(toParentViewController: nil)
})
} else {
rootViewController = nav
view.addSubview(nav.view)
nav.didMove(toParentViewController: self)
}
}
override var prefersStatusBarHidden : Bool {
switch rootViewController {
case is LaunchViewController:
return true
case is Home:
return false
default:
return false
}
}
}

AVKit – Video clips loop just 2 times

I have got four video clips and I want to play them endlessly. But my AVQueuePlayer() loops all the videos just 2 times and then stops.
How to make them play endlessly?
Here's my code:
import UIKit
import AVKit
class ViewController: UIViewController {
private let player = AVQueuePlayer()
let clips = ["001", "002", "003", "004"]
private var token: NSKeyValueObservation?
var avPlayerView = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
self.addAllVideosToPlayer()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
self.addAllVideosToPlayer()
}
func addAllVideosToPlayer() {
avPlayerView.player = player
for clip in clips {
let urlPath = Bundle.main.path(forResource: clip, ofType: "m4v")!
let url = URL(fileURLWithPath: urlPath)
let playerItem = AVPlayerItem(url: url)
player.insert(playerItem, after: player.items().last)
token = player.observe(\.currentItem) { [weak self] player, _ in
if self!.player.items().count == 1 { self?.addAllVideosToPlayer() }
}
avPlayerView.showsPlaybackControls = false
player.volume = 0.0
}
present(avPlayerView, animated: true, completion: { self.player.play() })
}
}
I solved my problem. I deleted viewDidLoad() method and placed present() function into viewDidAppear().
Here's how it looks like:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
self.addAllVideosToPlayer()
present(avPlayerView, animated: true, completion: { self.player.play() })
}

How to play video in ios swift

I am new to ios programming, actually I need to stream video URL but i am unable to stream video URL using avplayer, but using avplayer downloaded file i am able to play.Actual problem is my file format is different
for example my file name is like this song.apa but it is song.mp4
code:
let avplayerController = AVPlayerViewController()
var avPlayer:AVPlayer?
override func viewDidLoad()
{
super.viewDidLoad()
let movieUrl = URL.init(string: "http://techslides.com/demos/sample-videos/small.3gp")
self.avPlayer = AVPlayer.init(url: movieUrl!)
self.avplayerController.player = self.avPlayer
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playVideo(_ sender: Any)
{
self.present(self.avplayerController, animated: true) {
self.avplayerController.player?.play()
}
}
In Swift 3
import Foundation
import AVFoundation
import MediaPlayer
import AVKit
func play()
{
let player = AVPlayer(url: "Your Url")
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true)
{
playerViewController.player!.play()
}
}
You cant play this particular link (http://techslides.com/demos/sample-videos/small.3gp) using AVPlayer or AVPlayerViewController because that file is in AMR (Adaptive Multi-Rate, a format for speech) - which is not supported since iOS 4.3
Some of 3gp files can be played but only ones that have video and audio streams supported by Apple.
In Swift 3, try this code for playing video in project
import UIKit
import AVKit
import AVFoundation
import MediaPlayer
import MobileCoreServices
class VideoPlayerViewController: UIViewController,AVPlayerViewControllerDelegate {
//MARK: - Outlet -
#IBOutlet weak var viewVidioPlayer: UIView!
//MARK: - Variable
//MARK: - View Life Cycle -
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Action -
//for Playing Video
#IBAction func btnvideoPlayClicked(_ sender: UIButton) {
self.videoPlay()
}
func videoPlay()
{
let playerController = AVPlayerViewController()
playerController.delegate = self
let bundle = Bundle.main
let moviePath: String? = "http://techslides.com/demos/sample-videos/small.3gp"
let movieURL = URL(fileURLWithPath: moviePath!)
let player = AVPlayer(url: movieURL)
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
player.play()
}
//MARK: - other Function -
func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController){
print("playerViewControllerWillStartPictureInPicture")
}
func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStartPictureInPicture")
}
func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error)
{
print("failedToStartPictureInPictureWithError")
}
func playerViewControllerWillStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerWillStopPictureInPicture")
}
func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStopPictureInPicture")
}
func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool
{
print("playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart")
return true
}
}
I hope it's work for you,
thank you
heres an example of streaming video..
override func viewDidLoad() {
super.viewDidLoad()
let player = AVPlayer(url: URL(string: "http://techslides.com/demos/sample-videos/small.mp4")!)
let controller = AVPlayerViewController()
present(controller, animated: true) { _ in }
controller.player = player
addChildViewController(controller)
view.addSubview(controller.view)
controller.view.frame = CGRect(x: 50, y: 50, width: 300, height: 300)
controller.player = player
controller.showsPlaybackControls = true
player.isClosedCaptionDisplayEnabled = false
player.play()
}
you can use YoutubePlayerView for playing youtube videos, and for else formats you can use UIWebView. For doing so, simply use if-else block,
if movieUrl.contains("youtube.com/") {
var videoId: String = extractYoutubeId(fromLink: movieUrl)
youtubePlayerView.load(withVideoId: videoId)
} else {
webView = UIWebView(frame: CGRect(x: 0, y: 0, width: 288, height: 277))
webView.delegate = self
webView.backgroundColor = UIColor.black
webView?.loadRequest(movieUrl)
}
For Swift 3 play video from URL
//AVPlayerViewControllerDelegate // example : class TestAudioVideoVC: UIViewController,AVPlayerViewControllerDelegate
func videoPlay()
{
let playerController = AVPlayerViewController()
playerController.delegate = self
let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL! as URL)
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64)
playerController.showsPlaybackControls = true
player.play()
}
//MARK: - AVPlayerViewController Delegate -
func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController){
print("playerViewControllerWillStartPictureInPicture")
}
func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStartPictureInPicture")
}
func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error)
{
print("failedToStartPictureInPictureWithError")
}
func playerViewControllerWillStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerWillStopPictureInPicture")
}
func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStopPictureInPicture")
}
func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool
{
print("playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart")
return true
}
Play video in swift 5
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func playVideoUsingURL(_ sender: Any) {
playGlobalVideo()
}
#IBAction func playVideoFromLocalDrive(_ sender: Any) {
playLocalVideo()
}
func playGlobalVideo() {
guard let videoURL = URL(string: "http://static.videokart.ir/clip/100/480.mp4") else {
return
}
let player = AVPlayer(url: videoURL)
let vc = AVPlayerViewController()
vc.player = player
present(vc, animated: true) {
player.play()
}
}
func playLocalVideo() {
guard let videoPath = Bundle.main.path(forResource: "movie", ofType: "mov") else {
return
}
let player = AVPlayer(url: URL.init(fileURLWithPath: videoPath))
let playCtr = AVPlayerViewController()
playCtr.player = player
present(playCtr, animated: true) {
player.play()
}
}
}

Resources