首页 > 解决方案 > 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)")
        }
    }
}

标签: iosswift

解决方案


URL(fileURLWithPath一起absoluteString是错误的。

您必须编写(注意不同的URL初始化程序):

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

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

推荐阅读