如何解决Swift:从网址保存视频数据时出错
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 saving video: \(error.localizedDescription)")
}
}
在这里self.videoUrl
是摄像机录制的视频的url
,并通过委托方法func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediawithInfo info: [UIImagePickerController.InfoKey : Any])
[878 ] 13:22:16.045 | video | Main thread | error saving video: The folder “4A601A28-C4EB-405E-8110-6D01965D5920.mov” doesn’t exist.
我不确定这段代码有什么问题。如果文件不存在,那么我们如何首先创建文件,然后将数据写入文件中?
解决方法
好的,几天前,我有一个类似的任务(即下载视频,而不考虑URL源(本地还是远程),然后将其保存在本地)。
我使用您的函数进行了实验。
请参阅github存储库,其中包含有效的示例以及对函数的修复 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
编辑:要在每次构建项目时解决文档中文件丢失的问题,然后在我上面提供的仓库中查看更改。我添加了一个从文档文件夹中检索视频文件的修复程序。
所以基本上应该如何检索文件就是只保存fileName
,因为每次运行构建都会产生不同的filePath
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。