I am trying to store videos from a user's camera roll directly on the application itself using the following:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as! URL
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = String(Date().hashValue) + ".mp4"
let dataPathStr = documentsDirectory + "/" + fileName
url = dataPathStr
let dataPath = URL(fileURLWithPath: dataPathStr)
var videoData : NSData?
do {
try videoData = NSData(contentsOf: videoURL)
videoData?.write(to: dataPath, atomically: true)
} catch {
print("Error saving video:")
print(error)
}
self.dismiss(animated: true) {
self.performSegue(withIdentifier: "importToCrop", sender: self)
}
}
I have this working as I am able to access the video after storing it by using its URL (dataPath).
However, when I close and reopen the app, I can no longer the access via the same URL - It seems like the video is deleted once the app is closed.
Is there a way to check if the video is actually deleted or maybe is there a better way to store mp4 files on the application?
Figured it out -- turns out the way I saved the file above was correct, but what I didn't realize is that the path to the Documents directory changes with each run.
So, to get retrieve the a file stored in your Documents directory, you would have to get the url each time by the following:
func getVideoURL(fileName : String)-> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(fileName)
}