[英]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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.