如何将 MP4 文件直接存储和使用到 iOS 应用程序

How to store and use MP4 files directly to an iOS application

我正在尝试使用以下方法将用户相机胶卷中的视频直接存储在应用程序本身上:

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)
        }
    }

我有这个工作,因为我可以在使用 URL (dataPath) 存储视频后访问它。

但是,当我关闭并重新打开应用程序时,我无法再通过相同的方式访问URL - 应用程序关闭后视频似乎被删除了。

有没有办法检查视频是否真的被删除了,或者是否有更好的方法在应用程序上存储 mp4 文件?

想通了 -- 结果证明我上面保存文件的方式是正确的,但我没有意识到的是,Documents 目录的路径会随着每个 运行.

因此,要检索存储在您的 Documents 目录中的文件,您必须每次通过以下方式获取 url:

    func getVideoURL(fileName : String)-> URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(fileName)
    }