Swift3.0 fileAttributes 在现有文件上抛出 "no such file"错误

标签 swift swift3 file-attributes

<分区>

我是 Swift 的新手,我正在尝试实现文件创建日期检查。

想法是检查文件创建时间是否超过 7 天。由于某种原因,代码总是返回“没有这样的文件”错误。

为了检查哪里出了问题,我使用相同的路径在相同的函数中读取文件的内容,并且运行完美。

我使用的路径不正确还是我误解了什么?

func creationDateCheck(name: String) -> Bool {
    // This is the path I am using, file is in the favorites folder in the .documentsDirectory
    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let myFilesPath = documentsUrl.appendingPathComponent("favorites/" + name + ".xml")
    let pathString = "\(myFilesPath)"

    //First do block tries to get the file attributes and fails
    do {
        let fileAttributes = try FileManager.default.attributesOfItem(atPath: pathString)
        print(fileAttributes)
        let creationDate = (fileAttributes[FileAttributeKey.creationDate] as? NSDate)!

        return daysBetweenDates(endDate: creationDate as Date) > 7

    } catch let error as NSError {

        print(error.localizedDescription)
    }

    // Second do block reads from file successfully using the same path
    do {
        print(try String(contentsOf: myFilesPath, encoding: String.Encoding.utf8))
    }catch {print("***** ERROR READING FROM FILE *****")}

    return false
}

最佳答案

您不能直接使用 "\(myFilesPath)"URL 获取 String 而不是您需要使用 path URL 属性。

let fileAttributes = try FileManager.default.attributesOfItem(atPath: myFilesPath.path)

您成功读取文件内容的原因是您使用了 String(contentsOf:encoding:) 并且它将接受 URL 对象作为第一个参数。

关于Swift3.0 fileAttributes 在现有文件上抛出 "no such file"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631678/

相关文章:

swift - 如何记录 didReceiveRemoteNotification userInfo? - swift

c# - 在 C# .Net 2.0 中使用文件属性

ios - Swiftui - 如何使用环境对象作为参数初始化observedObject?

ios - 使用指针在 Parse 中查询行 (ios)

swift - 是否可以使用 Swift 评估 var/let?

os.removexattr 的 Python 文档—— '*'(星号)参数是什么意思?

Windows Batch,调用另一个批处理时的循环和文件属性

iOS 以 Data Swift 形式上传图片

objective-c - 在 Obj-C 类中找不到 Swift 协议(protocol)声明

ios - 如何在更改 View 的同时仍然让用户在 TextField 中进行编辑?