2016-11-16 6 views
2

저는 Swift에 매우 익숙하며 파일 생성 날짜 확인을 구현하려고합니다.Swift3.0 fileAttributes가 기존 파일에 "no such file"오류를 발생했습니다.

아이디어는 파일이 7 일보다 오래 생성되었는지 확인하는 것입니다. 어떤 이유로 코드는 항상 "no such file"오류를 반환합니다.

무엇이 잘못되었는지 확인하기 위해 동일한 기능을 사용하여 파일의 내용을 읽는 데 동일한 경로가 사용되고 완벽하게 작동합니다.

경로를 잘못 사용하고 있거나 잘못 이해하고 있습니까?

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 
} 

답변

4

직접 대신 당신이 URLpath 속성을 사용할 필요가 그 "\(myFilesPath)"를 사용 URL에서 String을 얻을 수 없습니다.

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

당신이 파일의 내용을 읽고있는 이유

성공적으로 당신이 String(contentsOf:encoding:)을 사용하고 그 첫 번째 매개 변수로 URL 객체를 받아 들일 것입니다.