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.
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 NSDictionaryattrs.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