我有以下保存录制视频的代码:
func saveVideo() -> Void {
guard let url = self.videoUrl else {
Logger.shared.log(.video, .error, "error video url invalid")
return
}
let homeDirectory = URL.init(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
let fileUrl = homeDirectory.appendingPathComponent(self.adId.toString()).appendingPathComponent("video-clip").appendingPathComponent(UUID.init().uuidString, isDirectory: false).appendingPathExtension("mov")
Logger.shared.log(.video, .debug, "saving video to: \(fileUrl)")
self.savedVideoUrl = fileUrl
do {
let data = try Data(contentsOf: url)
try data.write(to: fileUrl, options: .atomicWrite)
} catch {
Logger.shared.log(.video, .error, "error saving video: \(error.localizedDescription)")
}
}
在这里,self.videoUrl
是摄像机录制的视频的url
,由委托方法func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
初始化。
问题是,当saveVideo()
方法执行时,它会给出一个错误:
[878 ] 13:22:16.045 | video | Main thread | error saving video: The folder “4A601A28-C4EB-405E-8110-6D01965D5920.mov” doesn’t exist.
我不知道这个代码有什么问题。如果文件不存在,那么我们如何必须先创建文件,然后将数据写入其中?
发布于 2020-11-01 17:23:08
好吧,我几天前有个类似的任务。下载视频,不管网址来源(本地或远程),然后保存在本地)。
我用你的功能做了个实验。
参见github repo,附带工作示例并将修复应用于函数 https://github.com/glennposadas/AVFoundation-SaveLocal。
您所做的错误是为新文件提供URL路径的方式。
编辑:我认为您需要首先创建您的文件夹路径。我的fileUrl
工作是因为路径是存在的。
这样,它就能工作(.mp4或.mov,不管是哪种方式):
let fileUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
.first!
.appendingPathComponent("\(UUID.init().uuidString).mp4")
它有一个路径(如果要打印的话):
/Users/myusername/Library/Developer/CoreSimulator/Devices/812428A5-0893-43BE-B343-B23E9F13D4AA/data/Containers/Data/Application/E278E093-BE29-410B-9C5D-810BD0F968F8/Documents/F227C8B5-5D8D-42B0-8205-3ADAD0DD38F5.mp4
同时,您的fileUrl:
let homeDirectory = URL.init(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
let fileUrl = homeDirectory
.appendingPathComponent("someId")
.appendingPathComponent("video-clip")
.appendingPathComponent(UUID.init().uuidString, isDirectory: false)
.appendingPathExtension("mov")
给出路径:
/Users/myusername/Library/Developer/CoreSimulator/Devices/812428A5-0893-43BE-B343-B23E9F13D4AA/data/Containers/Data/Application/570D3CFA-3C44-41A5-A642-C79E5590D16E/someId/video-clip/5B1C9C98-C9EA-40D2-805C-B326466837E6.mov
编辑:要解决每次构建项目时文档中缺少文件的问题,请参阅上面提供的repo中的更改。我添加了一个修复程序,用于从文档文件夹检索视频文件。
因此,基本上您应该如何检索文件,只保存fileName
,因为构建的每一次运行都会产生不同的filePath
。
https://stackoverflow.com/questions/64630868
复制相似问题