iOS: How do you find the creation date of a file?
This code actually returns the good creation date to me:
NSFileManager* fm = [NSFileManager defaultManager];
NSDictionary* attrs = [fm attributesOfItemAtPath:path error:nil];
if (attrs != nil) {
NSDate *date = (NSDate*)[attrs objectForKey: NSFileCreationDate];
NSLog(@"Date Created: %@", [date description]);
}
else {
NSLog(@"Not found");
}
Are you creating the file inside the App? Maybe that's where the problem is.
Swift 2.0 version:
do {
let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(YOURPATH)
let creationDate = fileAttributes[NSFileCreationDate] as? NSDate
let modificationDate = fileAttributes[NSFileModificationDate] as? NSDate
print("creation date of file is", creationDate)
print("modification date of file is", modificationDate)
}catch let error as NSError {
print("file not found:", error)
}
There is a special message fileCreationDate
for that in NSDictionary
. The following works for me:
Objective-C:
NSDate *date = [attrs fileCreationDate];
Swift:
let attrs = try NSFileManager.defaultManager().attributesOfItemAtPath(path) as NSDictionary
attrs.fileCreationDate()
Updated answer for Swift 4 to pull out the modified (.modifiedDate
) or creation (.creationDate
) date:
let file: URL = ...
if let attributes = try? FileManager.default.attributesOfItem(atPath: file.path) as [FileAttributeKey: Any],
let creationDate = attributes[FileAttributeKey.creationDate] as? Date {
print(creationDate)
}
- Using a file that you provide in advance via a URL, it will request its attributes. If successful a dictionary of [FileAttributeKey: Any] is returned
- Using the dictionary from step 1, it then pulls out the creation date (or modified if you prefer) and using the conditional unwrap, assigns it to a date if successful
- Assuming the first two steps are successful, you now have a date that you can work with