Search code examples
swiftvideoavfoundationlocalavkit

video playing (AVPlayer ViewController, AVkit) is not working (Does not appear)


I searched for hours and found no solution ... The video playing code is not working (the local video doesn't appear...) I also try open video through open video with URL code they both did not work. hope you can find solution for that, thank you!

Code Below :

import UIKit
import AVKit
import AVFoundation

class ViewController2: UIViewController {

    func forbutton(name : String, type : String)  {
        func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            playVideo(name: name, type: type)
        }
    }


    private func playVideo(name : String, type : String) {
        guard let path = Bundle.main.path(forResource: "\(name)", ofType:"\(type)") else {
            debugPrint("video not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        let playerController = AVPlayerViewController()
        playerController.player = player
        present(playerController, animated: true) {
            player.play()
        }
    }




    @IBAction func fatB(_ sender: Any) {
        forbutton(name: "fatB", type: "mp4")

    }


    @IBAction func coderB(_ sender: Any) {

        forbutton(name: "birdC", type: "mp4")
    }


    @IBAction func clashB(_ sender: Any) {

        forbutton(name: "clash", type: "mp4")
    }

Solution

  • Currently you're inserting a function inside another , it should be

    func forbutton(name : String, type : String)  {
    
        playVideo(name: name, type: type)
    
    }
    

    If you want to play it when view appears

    func viewDidAppear(_ animated: Bool) {
    
        super.viewDidAppear(animated)
    
        forbutton(name: "fatB", type: "mp4")
    }