感谢此论坛中的各种有用帖子,我有一些代码可用于获取单个用户选择的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
{
}
答案 0 :(得分:9)
您可以按以下方式扩展网址:
extension URL {
var creationDate: Date? {
return (try? resourceValues(forKeys: [.creationDateKey]))?.creationDate
}
}
用法:
print(yourURL.creationDate)
答案 1 :(得分:1)
根据URL
和URLResourceValues
的标题文档,您可能需要编写如下内容:
(此代码假设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
。
答案 2 :(得分: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