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

问题描述 投票:3回答:3

由于此论坛中提供了许多有用的信息,我有一些代码可用于获取单个用户选择的NSURL的创建日期。但是,我无法使代码适用于硬编码的NSURL,也无法通过NSFileManager枚举器在循环中使用。

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

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

enter image description here

当我尝试将此代码添加到通过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
    {

    }
swift nsurl nsfilemanager swift3
3个回答
9
投票

您可以如下扩展URL:

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

用法:

print(yourURL.creationDate)

1
投票

根据URLURLResourceValues的标题文档,您可能需要编写如下内容:

(此代码假定chosenURL的类型为URL?。]

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

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

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

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


0
投票

快速5中,我使用以下代码:

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

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

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

有关FileAttributeKey的更多信息,请点击https://developer.apple.com/documentation/foundation/fileattributekey

© www.soinside.com 2019 - 2024. All rights reserved.