我正在我的應用程式中錄制視頻,我想保存該視頻并隨時播放。一切正常,但是當我重新打開應用程式時,該檔案不再可用(檔案 URL 中沒有資料)。
我就是這樣做的:
我錄制了一段視頻,然后等到代表來fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?)了。在這個函式中,我從 outputURL 中獲取資料,并首先將其保存在用戶的圖庫中,然后保存在 FileManager 本地目錄中:
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
if error == nil {
try? PHPhotoLibrary.shared().performChangesAndWait {
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputFileURL)
}
SVProgressHUD.show()
do {
if let data = try? Data(contentsOf: outputFileURL) {
let localDirectoryURL = self.saveToLocalDirectory(nameWithExtension: "\(randomString(length: 10)).mp4", data: data)
viewModel.outputVideoURL = localDirectoryURL ?? outputFileURL
viewModel.createAndSaveLocalVideo(url: localDirectoryURL ?? outputFileURL)
} else {
SVProgressHUD.showError(withStatus: "Something wrong happened")
}
}
}
func saveToLocalDirectory(nameWithExtension: String, data: Data) -> URL? {
guard let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return nil
}
let path = documentDirectoryPath.appendingPathComponent(nameWithExtension)
do {
try data.write(to: path)
return path
} catch {
print(error.localizedDescription)
return nil
}
}
我將檔案 URL 保存在 UserDefaults 中,然后嘗試播放它。如果我還沒有關閉應用程式,一切都會按預期進行。但是當我關閉應用程式并重新啟動它時,我得到:
Error Domain=NSCocoaErrorDomain Code=260 "The file “33eLKbc8kA.mp4” couldn’t be opened because there is no such file."
任何時候都不會拋出任何錯誤,正如我所提到的,當我嘗試在同一個應用程式會話中通過該 URL 重現它時,它可以完美運行。
現在我正在錄制 10-15 秒的視頻,但我將錄制長達 60 到 75 分鐘。它不是 4K 格式,當它是 60 分鐘的視頻時,它的重量約為 500mb。
我究竟做錯了什么?
uj5u.com熱心網友回復:
根據設計,每次重新打開應用程式時,檔案目錄的路徑都會改變。因此,您應該只保存 URL 的最后一部分(最有可能是檔案名),而不是保存完整的 URL。
因此,只需保存您的nameWithExtension然后通過類似的東西重新創建完整路徑
func urlForVideo(nameWithExtension: String) -> URL? {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(nameWithExtension)
}
并在加載和保存檔案時使用此代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/413430.html
標籤:
