0

I'm trying to play a video downloaded to the device's document directory. For some reason, it won't happen. All I get is this symbol:

enter image description here

Here's my code:

let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let videoFileUrl = URL(fileUrlWithPath: documentPath)
let videoFilePath = videoFileUrl.appendingPathComponent("somVideo.mp4").path
if FileManager.default.fileExists(atPath: videFilePath){
    let player = AVPlayer(url: URL(string: videoFilePath)!)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
    }
}
else {
    print("File doesn't exist")
}

The file exists at the location - I have checked my documents directory for the simulator - and the else statement isn't fired. Nothing else is printed to the console.

Any help would be appreciated.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
David Stenstrøm
  • 762
  • 1
  • 8
  • 22
  • 3
    You are passing `videoFileUrl` to the `AVPlayer`. Use `URL(string: videoFilePath)!` instead. `videoFileUrl` refers to the documents directory, whereas `videoFilePath` refers to the file itself. – Luke Van In Jan 10 '17 at 10:31
  • Oups - that was a typo- I've fixed the code. – David Stenstrøm Jan 10 '17 at 10:38
  • 1
    Do not – ever – use `URL(string:` for a string path in the file system. You **must** use `URL(fileURLWithPath:` (URL with capital letters!) because only this initializer adds the `file://` scheme. It's not very useful anyway to recreate an URL from a path of an URL. – vadian Jan 10 '17 at 18:08

1 Answers1

3

Here's the answer the OP edited into the question (and which was subsequently rolled back because answers should be answers). If OP posts a separate answer, I'll remove this one.


I managed to get it working with a little help from a colleague of mine. Here's the answer if anyone should be interested:

let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let docDir : URL = urls.first {
    let videoUrl = docDir.appendingPathComponent("\(objectId).mp4")
    do {
        let videoExists : Bool = try videoUrl.checkResourceIsReachable()
        if videoExists {
            let player = AVPlayer(url: videoUrl)
            let playerController = AVPlayerViewController()
            playerController.player = player
            self.present(playerController, animated: true) {
                playerController.player!.play()
            }
        }
        else {
            print("Video doesn't exist")
        }
    }
    catch let error as NSError {
        print(error)
    }
}
Caleb
  • 124,013
  • 19
  • 183
  • 272