ios - iOS / Swift无法将文件写入将文件路径视为目录路径
问题描述
我有以下 swift 函数,我希望将传入的字节保存到 iOS 上的 JPEG 文件中。不幸的是,调用 data.write 引发异常,我收到错误消息
文件夹“studioframe0.jpg”不存在。写入文件:/var/mobile/Containers/Data/Application/2A504F84-E8B7-42F8-B8C3-3D0A53C1E11A/Documents/studioframe0.jpg -- file:///
为什么iOS认为它是一个不存在的目录的目录路径,而不是我要求它写入的文件?
func saveToFile(data: Data){
if savedImageCount < 10 {
guard let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("studioframe\(savedImageCount).jpg").absoluteString)
savedImageCount += 1
do {
try data.write(to: imgPath, options: .atomic)
print("Saved \(imgPath) to disk")
} catch let error {
print("\(error.localizedDescription) writing to \(imgPath)")
}
}
}
解决方案
URL(fileURLWithPath
一起absoluteString
是错误的。
您必须编写(注意不同的URL
初始化程序):
let imgPath = URL(string: documentDirectoryPath.appendingPathComponent("studioframe\(savedImageCount).jpg").absoluteString)
但是这个(URL
→→ String
)URL
很麻烦,有一个更简单的解决方案,请考虑(字符串)路径和URL之间的区别
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! // the Documents directory is guaranteed to exist.
let imgURL = documentDirectoryURL.appendingPathComponent("studioframe\(savedImageCount).jpg")
...
try data.write(to: imgURL, options: .atomic)
推荐阅读
- rest - HTTP:需要更改密码时返回什么响应?
- javascript - 谷歌测速移动设备上出现重力表单插件怎么解决?
- javascript - 反应钩子useState()的真正奇怪的行为
- ruby-on-rails - BookingsController#create 中的 ActiveRecord::RecordNotFound 找不到没有 ID 的酒店
- python - 在一个语句中替换多个字符
- java - 用于 Java 的 opencv VideoWriter 在 MacOS 上无法按预期工作
- c++ - 类析构函数中的 delete 关键字有什么问题?
- python - (Python)“matplotlib”在我的 Pycharm 中不起作用
- python - 如何去歪斜文本图像也检索该图像的新边界框?
- spring-boot - 使用 spock 测试 Spring 启动