2016-11-16 1 views
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 
} 

答えて

4

あなたはURLpathプロパティを使用する必要があること"\(myFilesPath)"を使用しての代わりに、直接URLからStringを得ることができません。

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

あなたが成功したファイルの内容を読んでいる理由は、あなたがString(contentsOf:encoding:)を使用していると、それは最初のパラメータとしてURLオブジェクトを受け入れることです。

関連する問題