How can I get the file creation date using URL resourceValues method in Swift 3?

落花浮王杯 提交于 2019-12-06 04:23:10

You can extend URL as follow:

extension URL {
    var creationDate: Date? {
        return (try? resourceValues(forKeys: [.creationDateKey]))?.creationDate
    }
}

usage:

print(yourURL.creationDate)

According to the header doc of URL and URLResourceValues, you may need to write something like this:

(This code is assuming chosenURL is of type URL?.)

do {
    if
        let resValues = try chosenURL?.resourceValues(forKeys: [.creationDateKey]),
        let createDate = resValues.creationDate
    {
        //Use createDate here...
    }
} catch {
    //...
}

(If your chosenURL is of type NSURL?, try this code.)

do {
    if
        let resValues = try (chosenURL as URL?)?.resourceValues(forKeys: [.creationDateKey]),
        let createDate = resValues.creationDate
    {
        //Use createDate here...
        print(createDate)
    }
} catch {
    //...
}

I recommend you to use URL rather than NSURL, as far as you can.

in swift 5 I use the following code:

let attributes = try! FileManager.default.attributesOfItem(atPath: item.path)
let creationDate = attributes[.creationDate] as! Date

sort array with the following code

fileArray = fileArray.sorted(by: {
        $0.creationDate.compare($1.creationDate) == .orderedDescending
    })

more about FileAttributeKey here: https://developer.apple.com/documentation/foundation/fileattributekey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!