我对Swift还是很陌生,我想在录制视频后将视频保存到documents文件夹(这样我就可以上传到服务器了),但是出现上述错误。我知道错误在说什么,但不确定如何解决。我从堆栈上的另一个答案得到下面的代码。 我想念什么?
此行的构建失败:
videoData?.write(toFile: dataPath, atomically: false)
完整功能是:
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as! NSURL
let videoData = NSData(contentsOf: videoURL as URL)
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docsDirectory = getDocumentsDirectory()
let dataPath = docsDirectory.appendingPathComponent("/videoFileName.mp4")
videoData?.write(toFile: dataPath, atomically: false)
self.dismiss(animated: true, completion: nil)
}
答案 0 :(得分:0)
只需使用数据方法write(to: URL)
而不是write(foFile: String)
或传递URL
path属性。顺便说一下,URL
数据路径的命名具有误导性。将其更改为fileURL
并传递其路径fileURL.path
,但最好在可能的情况下使用URL
方法。同样,正如@vadian的注释中已经提到的那样,在附加路径组件时,无需强制转换为NSURL
并返回至URL
并且不需要传递斜杠。 NSData
同样适用,只要有可能,都应删除NS
前缀。 Swift本机类型为Data
。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
if let videoURL = info[.mediaURL] as? URL {
do {
let videoData = try Data(contentsOf: videoURL)
let fileURL = documentsDirectory.appendingPathComponent("videoFileName.mp4")
try videoData.write(to: fileURL)
// pass atomic options if you would like to automatically override any existing file if needed
// try videoData.write(to: fileURL, options: .atomic)
} catch {
print(error)
}
dismiss(animated: true)
}
}