Search code examples
swiftswift3file-attributes

Swift3.0 fileAttributes throws "no such file" error on existing file


I am quite new to Swift and I am trying to implement a file creation date check.

The idea is to check if the file was created longer than 7 days ago. For some reason the code always returns "no such file" error.

To check what is wrong i used the same path to read the contents of the file in the same function and that works flawlessly.

Am I using the path incorrectly or have I misunderstood something?

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
}

Solution

  • You can not get String from URL directly using "\(myFilesPath)" instead of that you need to use path property of URL.

    let fileAttributes = try FileManager.default.attributesOfItem(atPath: myFilesPath.path)
    

    The reason you are reading content of file successfully is that you have used String(contentsOf:encoding:) and it will accept URL object as first parameter.