AVPlayerViewController не воспроизводит видео?

Я разрабатываю приложение для iOS, и я создал код, в котором после выбора ячейки в табличном представлении он переходит к AVPlayerViewController и воспроизводит локальный видеоклип в зависимости от того, какая строка ячейки была выбрана. Однако, когда он переходит к AVPlayerViewController, проигрыватель появляется, но видео не воспроизводится, почему это так? Я даже добавил оператор печати в функцию didSelectAtRow, чтобы убедиться, что выбран правильный видеофайл. Следует отметить, что код работает нормально до тех пор, пока не придет время воспроизвести видеофайл (проигрыватель появляется, но остается пустым).

import UIKit
import AVKit
import AVFoundation

class DrillsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var initialRow = Int()
var arrayForKey2 = [[String]]()
var keyIndex = Int()
var headLabel = String()
var labels = Array(trainingDict.keys)
var playerViewController = AVPlayerViewController()
var player = AVPlayer()
var videoURL = [URL]()
var videoUrl = [URL]()
var drillVid = URL(fileURLWithPath: String())

var firstTips = ["Tip 1: Stay Hydrated", "Tip 1: Keep elbow tucked", "x", "Tip 1: Take quick breaks:", "Tip 1: Keep your head up", "Tip 1: Don't cross your feet", "Tip 1: Don't do more than 15 reps"]


@IBOutlet weak var tableView: DrillsTableView!

@IBOutlet weak var drillLabel: UILabel!

@IBOutlet weak var labelBackground: UIView!

@IBAction func back(_ sender: Any) {

    dismiss(animated: true, completion: nil)
}

override func viewDidLoad() {
    super.viewDidLoad()

    videoURL = [URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/LowDribble.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallBBw:Pound.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallBBw:PickUp.mp4"), URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallBB.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallInOut.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallOverDribble.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallThruHoop.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallThruLeg.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallThruLegLo.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallWiper.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallIOBBCrossCombo.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallIOBetweenLegsCombo.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallComboFreestyle.mp4")]

    videoUrl = [URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallBBw:Pound.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallBtwLegwPound.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallCrosswPound.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallHiLo.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/OneBallThruHoop.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallIOw:Wiper.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallJuggle.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallInOut.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwoBallWiper.mp4"),URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BHB DrillVids/TwpBallOverDribble.mp4")]



    tableView.delegate = self
    tableView.dataSource = self
    drillLabel.text = labels[keyIndex]

    playerViewController.player = player



    for (key, value) in trainingDict {
        print("\(key) --> \(value)")
        objectArray.append(Objects(sectionName: key, sectionObjects: value))
    }
}




func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DrillsTableViewCell




    if initialRow == 1 {
    drillVid = videoURL[indexPath.row]

    }

    if initialRow == 2 {
        drillVid = videoUrl[indexPath.row]
    }

    print(initialRow)
    print(indexPath.row)
    print(drillVid)

}

//changes KeysController tip labels accordingly 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "Tips" {
        if let keysVC = segue.destination as? KeysController {


            keysVC.keyTip1 = firstTips[initialRow]
        }
        if segue.identifier == "playDrill", initialRow == 1 {
            if let indexPath = self.tableView.indexPathForSelectedRow {
                    drillVid = videoURL[indexPath.row]
                    let destination = segue.destination as! AVPlayerViewController
                    destination.player = playerViewController.player
                    playerViewController.player = player
                    player = AVPlayer(url: drillVid)
                    player.play()



                }

                if initialRow == 3 {
                    if let indexPath = self.tableView.indexPathForSelectedRow {
                    let video = videoUrl[indexPath.row]
                    let destination = segue.destination as! AVPlayerViewController
                    destination.player = AVPlayer(url: video)
                    destination.player?.play()
                }
            }
        }


    }
}

person Marko Cain    schedule 16.09.2017    source источник
comment
Я думаю, что ваш видео путь неверен. Теперь ваш путь к видеофайлу находится там, где видео находится на вашем рабочем столе. Вы должны добавить видеофайлы в свой проект, а затем получить доступ к этим видеофайлам.   -  person Vini App    schedule 17.09.2017
comment
Я добавил файлы в свой проект   -  person Marko Cain    schedule 17.09.2017


Ответы (1)


Если вы уже добавили эти файлы в проект, вам необходимо получить доступ к этим файлам, как показано ниже:

videoURL = [URL(fileURLWithPath: Bundle.main.path(forResource: "LowDribble", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallBBw:Pound", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallBBw:PickUp", ofType: "mp4")!), URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallBB", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallInOut", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallOverDribble", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallThruHoop", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallThruLeg", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallThruLegLo", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallWiper", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallIOBBCrossCombo", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallIOBetweenLegsCombo", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallComboFreestyle", ofType: "mp4")!)]

videoUrl = [URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallBBw:Pound", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallBtwLegwPound", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallCrosswPound", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallHiLo", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "OneBallThruHoop", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallIOw:Wiper", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallJuggle", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallInOut", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwoBallWiper", ofType: "mp4")!),URL(fileURLWithPath: Bundle.main.path(forResource: "TwpBallOverDribble", ofType: "mp4")!)]
person Vini App    schedule 17.09.2017
comment
Спасибо вам за вашу помощь! - person Marko Cain; 18.09.2017
comment
Теперь я получаю сообщение об ошибке, в котором говорится, что я разворачиваю необязательное значение, равное нулю. Какие-либо предложения? - person Marko Cain; 18.09.2017
comment
Не работает, я получаю фатальную ошибку, которая говорит, что я нахожу ноль при развертывании необязательного - person Marko Cain; 18.09.2017
comment
Используйте это: 'guard let path = Bundle.main.path (forResource: YourvideoFileName, ofType: mp4) else { debugPrint (YourvideoFileName.mp4 not found) return }' this ссылка может помочь - person Imrul Kayes; 01.10.2017