【问题标题】:iOS / Swift failing to write file as treating file path as directory path [duplicate]iOS / Swift无法将文件写入将文件路径视为目录路径[重复]
【发布时间】:2019-06-10 19:44:39
【问题描述】:

我有以下 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)")
        }
    }
}

【问题讨论】:

  • 这应该重新打开,uiimage 问题是另外一回事。这里的问题是尚未创建中间目录。这可以通过文件管理器创建,然后它将不再将一个人的文件与文件夹混淆。接受的答案是一个很好的解决方法,但没有解决缺少目录的核心问题。

标签: ios swift


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    相关资源
    最近更新 更多