iOS/Swift 无法将文件写入为将文件路径视为目录路径

标签 ios swift

<分区>

我有以下 swift 函数,我希望它能将传入的字节保存到 iOS 上的 JPEG 文件中。不幸的是,调用 data.write 引发了异常,我收到了错误消息

The folder “studioframe0.jpg” doesn’t exist. writing to file:/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(fileURLWithPathabsoluteString 是错误的。

您必须编写(注意不同的 URL 初始值设定项):

let imgPath = URL(string: documentDirectoryPath.appendingPathComponent("studioframe\(savedImageCount).jpg").absoluteString)

但是这个(URLStringURL) 很麻烦,有一个更简单的解决方案,请考虑 (字符串)路径和 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)

关于iOS/Swift 无法将文件写入为将文件路径视为目录路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54221857/

相关文章:

android - 关于selendroid和appium的几个问题

ios - 如何使用选项卡和导航 Controller 实例化 View Controller 以进行深度链接?

ios - Tableview 不会 reloadData()

json - 使用 Swift 从 JSON 数组填充 UITableView

arrays - 扩展数组以支持自定义日志记录

iphone - 类似于 Monotouch 的 NSDateFormatterMediumStyle 的日期格式?

ios - EXPO app 出现在 iOS 上时闪烁,但 Android 没问题。它是由 EXPO 自动创建的( react 导航)

ios - 使用相机模式拍摄图像时出错

swift - 单击自定义单元格的 UITextField 后重新加载 TableView

objective-c - Swift 只读外部,可读写内部属性