如何使用 Swift 3 中的 URL resourceValues 方法获取文件创建日期?

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

感谢这个论坛中的各种有用的帖子,我有一些代码可以用于获取单个用户选择的 NSURL 的创建日期。但是,我无法让代码为硬编码的 NSURL 工作,也无法在通过 NSFileManager 枚举器的循环中工作。

我不是专业程序员;我制作的应用程序是办公工具。我的最终目标是根据创建日期简单地对 NSURL 对象数组进行排序。

我正在使用的代码如下,其功能正常,但如果我尝试使用注释行来评估特定的 PDF 文件,我会收到以下错误:

当我尝试将此代码添加到通过 NSFileManager 枚举器获取的 NSURL 对象循环时,我遇到了完全相同的错误。

我想不出如何使用错误指令来解决问题。如果有人可以提供帮助,那将是巨大的。谢谢。

let chosenURL = NSOpenPanel().selectFile

    //let chosenURL = NSURL.fileURL(withPath: "/Users/craigsmith/Desktop/PDFRotator Introduction.pdf")

    do
    {
        var cr:AnyObject?
        try chosenURL?.getResourceValue(&cr, forKey: URLResourceKey.creationDateKey)

        if (cr != nil)
        {
            if let createDate = cr as? NSDate
            {
                print("Seems to be a date: \(createDate)")

                let theComparison = createDate.compare(NSDate() as Date)

                print("Result of Comparison: \(theComparison)")  // Useless

                let interval = createDate.timeIntervalSinceNow

                print("Interval: \(interval)")

                if interval < (60*60*24*7*(-1))
                {
                    print("More than a week ago")

                }
                else
                {
                    print("Less than a week ago")
                }
            }
            else
            {
                print("Not a Date")
            }
        }
    }
    catch
    {

    }

根据URLURLResourceValues的header doc,你可能需要这样写:

(此代码假设 chosenURL 的类型为 URL?。)

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

(如果您的 chosenURLNSURL? 类型,请尝试此代码。)

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

我建议您尽可能使用 URL 而不是 NSURL

您可以按如下方式扩展 URL:

extension URL {
    /// The time at which the resource was created.
    /// This key corresponds to an Date value, or nil if the volume doesn't support creation dates.
    /// A resource’s creationDateKey value should be less than or equal to the resource’s contentModificationDateKey and contentAccessDateKey values. Otherwise, the file system may change the creationDateKey to the lesser of those values.
    var creation: Date? {
        get {
            return (try? resourceValues(forKeys: [.creationDateKey]))?.creationDate
        }
        set {
            var resourceValues = URLResourceValues()
            resourceValues.creationDate = newValue
            try? setResourceValues(resourceValues)
        }
    }
    /// The time at which the resource was most recently modified.
    /// This key corresponds to an Date value, or nil if the volume doesn't support modification dates.
    var contentModification: Date? {
        get {
            return (try? resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
        }
        set {
            var resourceValues = URLResourceValues()
            resourceValues.contentModificationDate = newValue
            try? setResourceValues(resourceValues)
        }
    }
    /// The time at which the resource was most recently accessed.
    /// This key corresponds to an Date value, or nil if the volume doesn't support access dates.
    ///  When you set the contentAccessDateKey for a resource, also set contentModificationDateKey in the same call to the setResourceValues(_:) method. Otherwise, the file system may set the contentAccessDateKey value to the current contentModificationDateKey value.
    var contentAccess: Date? {
        get {
            return (try? resourceValues(forKeys: [.contentAccessDateKey]))?.contentAccessDate
        }
        // Beginning in macOS 10.13, iOS 11, watchOS 4, tvOS 11, and later, contentAccessDateKey is read-write. Attempts to set a value for this file resource property on earlier systems are ignored.
        set {
            var resourceValues = URLResourceValues()
            resourceValues.contentAccessDate = newValue
            try? setResourceValues(resourceValues)
        }
    }
}

用法:

print(yourURL.creationDate)

in swift 5 我使用下面的代码:

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

使用以下代码对数组进行排序

fileArray = fileArray.sorted(by: {
        [=11=].creationDate.compare(.creationDate) == .orderedDescending
    })

更多关于 FileAttributeKey 的信息:https://developer.apple.com/documentation/foundation/fileattributekey