gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:37 24 4
gpt4 key购买 nike

<分区>

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com