如何将文件存储在使用“ documentDirectory” swift创建的文件夹中

时间:2019-01-21 13:14:43

标签: ios swift

我正在使用带有以下代码的createDirectory创建新文件夹。

    *let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    // Get documents folder
    let documentsDirectory: String = paths.first ?? ""
    // Get your folder path
    let dataPath = documentsDirectory + "/MyNewFolder"
    print("Path\(dataPath)")
    if !FileManager.default.fileExists(atPath: dataPath) {
        // Creates that folder if no exists
        try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
    }*

现在,我想在“ MyNewFolder”下存储新文件,例如log.text。有人可以建议我如何在“ MyNewFolder”文件夹下保存新文件吗

谢谢。

3 个答案:

答案 0 :(得分:2)

NSSearchPathForDirectoriesInDomains已过时。推荐的API是FileManager

与URL相关的API
let folderName = "MyNewFolder"
let fileManager = FileManager.default
let documentsFolder = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let folderURL = documentsFolder.appendingPathComponent(folderName)
let folderExists = (try? folderURL.checkResourceIsReachable()) ?? false
do {
    if !folderExists {
        try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: false)
    }
    let fileURL = folderURL.appendingPathComponent("log.txt")
    let hello = Data("hello".utf8)
    try hello.write(to: fileURL)

} catch { print(error) }

强烈建议不要通过串联字符串来构建路径。

答案 1 :(得分:1)

您可以尝试

try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)

do { 

    let sto =  URL(fileURLWithPath: dataPath + "log.txt")  // or let sto =  URL(fileURLWithPath: dataPath + "/log.txt") 

    try Data("SomeValue".utf8).write(to: sto)

    let read = try Data(contentsOf: sto)

    print(String(data: read, encoding: .utf8)!)
}
catch {

    print(error)
}

答案 2 :(得分:0)

let filePath = dataPath + "/log.txt"
FileManager.default.createFile(filePath, contents:dataWithFileContents, attributes:nil)