2016-11-16 32 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

直接使用"\(myFilesPath)"而不是您需要使用的URLpath財產不能得到URLString

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

您正在閱讀文件的內容之所以成功是你曾經使用過String(contentsOf:encoding:),它會接受URL對象作爲第一個參數。

相關問題