代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

我们应该什么时候使用FileManager。违约URL与NSSearchPathForDirectories相对?

  •  0
  • Cheok Yan Cheng  · 技术社区  · 3 年前

    目前,如果我想在Document directory中创建目录层次结构,我将执行以下操作


    使用NSSearchPathForDirectoriesInDomains(工作正常)

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let documentUrl1 = URL(string: documentsDirectory)!
    //
    // /Users/yccheok/Library/Developer/...
    //
    print("documentUrl1 -> \(documentUrl1)")
    
    let dataPath = documentUrl1.appendingPathComponent("SubFolder1").appendingPathComponent("SubFolder2")
    print("dataPath.absoluteString -> \(dataPath.absoluteString)")
    if !FileManager.default.fileExists(atPath: dataPath.absoluteString) {
        do {
            try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
            print("Folder creation done!")
        } catch {
            print(error.localizedDescription)
        }
    }
    

    但是,如果我使用下面的

    使用文件管理器。违约URL(不工作)

    let documentUrl0 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    //
    // file:///Users/yccheok/Library/Developer/...
    //
    print("documentUrl0 -> \(documentUrl0)")
    
    let dataPath = documentUrl0.appendingPathComponent("SubFolder1").appendingPathComponent("SubFolder2")
    print("dataPath.absoluteString -> \(dataPath.absoluteString)")
    if !FileManager.default.fileExists(atPath: dataPath.absoluteString) {
        do {
            try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
            print("Folder creation done!")
        } catch {
            print(error.localizedDescription)
        }
    }
    

    将打印以下错误

    无法保存文件子文件夹2,因为该卷是只读的。


    我想知道,在什么用例下 FileManager.default.urls 会有用吗?谢谢

    0 回复  |  直到 3 年前
        1
  •  3
  •   vadian    3 年前

    URL(string absoluteString 使用文件系统路径的API是错误的。

    你的代码意外工作是因为 URL(字符串) 适用于 路径 创建路径而不是有效的URL 绝对字符串 应用于路径会返回路径,因为没有方案( file:// ).

    然而,你被强烈劝阻不要这样做。必须使用创建文件系统URL URL(fileURLWithPath 你可以通过 path 所有物

    我们鼓励您使用 FileManager API,因为它提供了更好的错误处理,还提供了与URL相关的API,这是优于字符串路径API的首选。

    这是正确的 文件管理器 创建不存在的目录的方法

    let fm = FileManager.default
    do {
        let documentUrl = try fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        //
        // file:///Users/yccheok/Library/Developer/...
        //
        print("documentUrl -> \(documentUrl)")
        
        let dataURL = documentUrl.appendingPathComponent("SubFolder1").appendingPathComponent("SubFolder2")
        print("dataPath.path -> \(dataURL.path)")
        if !fm.fileExists(atPath: dataURL.path) {
            try fm.createDirectory(at: dataURL, withIntermediateDirectories: true, attributes: nil)
            print("Folder creation done!")
        }
    } catch { print(error) }