Swift3.0文件属性抛出;“没有此类文件”;现有文件出错

Swift3.0文件属性抛出;“没有此类文件”;现有文件出错,swift,swift3,file-attributes,Swift,Swift3,File Attributes,我是Swift的新手,我正在尝试执行文件创建日期检查 这样做的目的是检查文件创建的时间是否超过7天前。由于某些原因,代码总是返回“无此类文件”错误 为了检查什么是错误的,我使用相同的路径在相同的函数中读取文件的内容,并且工作正常 我是否使用了错误的路径,或者我误解了什么 func creationDateCheck(name: String) -> Bool { // This is the path I am using, file is in the favorites fol

我是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
,而需要使用
URL
path
属性

let fileAttributes = try FileManager.default.attributesOfItem(atPath: myFilesPath.path)
您成功读取文件内容的原因是您使用了
字符串(contentsOf:encoding:)
,并且它将接受
URL
对象作为第一个参数