Swift3.0 fileAttributes在现有文件上抛出“没有这样的文件”错误
问题描述:
我对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
}
答
直接使用"\(myFilesPath)"
而不是您需要使用的URL
path
财产不能得到URL
String
。
let fileAttributes = try FileManager.default.attributesOfItem(atPath: myFilesPath.path)
您正在阅读文件的内容之所以成功是你曾经使用过String(contentsOf:encoding:)
,它会接受URL
对象作为第一个参数。