Thanks to a variety of helpful posts in this forum, I have some code that works for obtaining the Creation Date of a single user-selected NSURL. However, I cannot get the code to work for either a hard-coded NSURL, nor within a loop through an NSFileManager enumerator.
I am not a professional programmer; I make apps that are tools for office. My ultimate goal is to simply sort an Array of NSURL objects based on Creation Date.
The code I am using is below, which functions just fine as is, but if I try to use the commented line to evaluate a specific PDF file, I get the following error:
I get the exact same error when I try to add this code to a loop of NSURL objects procured via the NSFileManager Enumerator.
I cannot figure out how to use the error instruction to solve the problem. If anyone can assist, that would be tremendous. Thank you.
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
{
}
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
来源:https://stackoverflow.com/questions/39500685/how-can-i-get-the-file-creation-date-using-url-resourcevalues-method-in-swift-3