Problem with get path to a subfolder in main bundle in AVPlayer

Viewed 576

I'm improving the code I have for my project.

I stuck with the process of calling videos by subfolders because the code reads all the mp4 files, it finds.

Applying different codes that I have found on the internet, but I end up breaking all the code without success. I would appreciate help or advice in this regard.

Attached image that shows the location of folders with the different videos that I would like to separate my view basic and intermediate folder import UIKit import AVKit import AVFoundation

class BasicLevel: UIViewController, UITableViewDataSource, UITableViewDelegate, AVPlayerViewControllerDelegate{

    var videoArray = [String]()

    @IBOutlet weak var videoView: UIView!
    @IBOutlet weak var videoTableView: UITableView!

    var videoVC = AVPlayerViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        videoTableView.delegate = self
        videoTableView.dataSource = self

        videoView.addSubview(videoVC.view)
        videoVC.view.frame = videoView.frame
        videoVC.showsPlaybackControls = false

        let filemanager = FileManager.default
        let path = Bundle.main.resourcePath!

        let allItems = try? filemanager.contentsOfDirectory(atPath: path)

        for singleItem in allItems! {
            if singleItem.hasSuffix("mp4") {
                videoArray.append(singleItem)
            }
        }

        if videoArray.count > 0 {
            playTopVideo(value: 0)
        }
    }

    func playTopVideo(value: Int) {
        let nameComponent = videoArray[value].components(separatedBy: ".")
        let name = nameComponent[0]

        let path = Bundle.main.path(forResource: name, ofType: "mp4")
        let url = URL(fileURLWithPath: path!)


        videoVC.player = AVPlayer(url: url)

        videoVC.player?.play()
    }
}
1 Answers

First of all you are responsible for creating the directory structure of the bundle so don't mess it up.

Secondly use the URL related API.

For example put all mp4 files in a subdirectory named videos. It's crucial that you create a real blue folder rather than a group (yellow) folder.

This would reduce your code to

var videoArray = [URL]()

override func viewDidLoad() {
    super.viewDidLoad()

    videoTableView.delegate = self
    videoTableView.dataSource = self

    videoView.addSubview(videoVC.view)
    videoVC.view.frame = videoView.frame
    videoVC.showsPlaybackControls = false

    videoArray = Bundle.main.urls(forResourcesWithExtension: "mp4", subdirectory: "videos")!
    playTopVideo(value: 0)
}

func playTopVideo(value: Int) {
    let videoURL = videoArray[value]
    videoVC.player = AVPlayer(url: videoURL)
    videoVC.player?.play()
}
Related