代码之家  ›  专栏  ›  技术社区  ›  dumbledad

ios/swift无法将文件写入为将文件路径视为目录路径[重复]

  •  0
  • dumbledad  · 技术社区  · 6 年前

    我有下面的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)")
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   vadian    6 年前

    URL(fileURLWithPath 一起 absoluteString 是错的。

    你必须写(注意不同的 URL 初始化器):

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

    但是这个( 统一资源定位地址 艾斯 String 艾斯 统一资源定位地址 )非常麻烦,有一个更简单的解决方案,请考虑(字符串)路径和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)