<分区>
我是 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
}