Nicholas Nicholas - 6 months ago 32
Swift Question

Parse Video Upload - Fatal error: unexpectedly found nil while unwrapping an Optional Value

I am trying to upload a video to Parse

If I just try to upload the video like so:

let videoData = NSData(contentsOfURL: url)
let videoFile = PFFile(name: "video.mov", data: videoData)
videoUploadObject["Video"] = videoFile


I will receive the error. I tried to remove this by running something like the following.

Main.sharedMain.userVideoOutputURL


returns:

file:///private/var/mobile/Containers/Data/Application/3B78A154-4340-432B-817A-2857EBA8064A/tmp/video.mov


Here is my full code:

let url = Main.sharedMain.userVideoOutputURL!

if let videoData = NSData(contentsOfURL: url) {

let videoFile = PFFile(name: "video.mov", data: videoData)
videoUploadObject["Video"] = videoFile


print("Video File \(videoFile)")


} else {
print("Else")
}


Else is always printed? What can I do to fix this? Thank you!

Answer

The URL looks fine (iOS doesn't use "/User/blah/blah/blah" for applicaion storage).

My first thought would be to check the data is writing correctly. NSData has a "writeToFile: options:" method that returns a bool. This will return false if writing has failed, and also throw an error which should give you some extra information.

let url = <YOUR_URL>
do {
    // put your options in here
    try data.writeToURL(url, options: NSDataWritingOptions.DataWritingAtomic)
} catch _ {
    print(error.localizedDescription)
}

If writing has succeeded, then you'll want to try loading the data using "contentsWithUrl: options:". This also throws an error if it fails, and so using the "localisedDescription" property of the thrown error object you should be able to get to the bottom of why it isn't loading.

let url = <YOUR_URL>
var data: NSData? = nil
do {
    // put your options in here
    try data = NSData(contentsOfURL: url, options: NSDataReadingOptions.DataReadingUncached)
} catch _ {
    print(error.localizedDescription)
}

Hope that helps :)