2
私はSwiftにはかなり新しく、ファイル作成日のチェックを実装しようとしています。Swift3.0 fileAttributesが既存のファイルに「このようなファイルはありません」というエラーをスローします
考えられるのは、ファイルが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
}