How to determine the date an app is installed or used for the first time?
Using the creation date of Documents directory is the best solution so far. Reproducing it in Swift 5.0
var inferredDateInstalledOn: Date? {
guard
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last,
let attributes = try? FileManager.default.attributesOfItem(atPath: documentsURL.path)
else { return nil }
return attributes[.creationDate] as? Date
}
To get the installation date, check the creation date of the Documents folder.
NSURL* urlToDocumentsFolder = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
__autoreleasing NSError *error;
NSDate *installDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:urlToDocumentsFolder.path error:&error] objectForKey:NSFileCreationDate];
NSLog(@"This app was installed by the user on %@", installDate);
To get the date of the last App update, check the modification date of the App bundle itself
NSString* pathToInfoPlist = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
NSString* pathToAppBundle = [pathToInfoPlist stringByDeletingLastPathComponent];
NSDate *updateDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:pathToAppBundle error:&error] objectForKey:NSFileModificationDate];
NSLog(@"This app was updated by the user on %@", updateDate);
NSDate *installDate = [[NSUserDefaults standardUserDefaults]objectForKey:@"installDate"];
if (!installDate) {
//no date is present
//this app has not run before
NSDate *todaysDate = [NSDate date];
[[NSUserDefaults standardUserDefaults]setObject:todaysDate forKey:@"installDate"];
[[NSUserDefaults standardUserDefaults]synchronize];
//nothing more to do?
} else {
//date is found
NSDate *todaysDate = [NSDate date];
//compare todaysDate with installDate
//if enough time has passed, yada yada,
//apply updates, etc.
}
My solution would be to check the last modified date of one of the files in the app bundle.
NSString *sourceFile = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Icon.png"];
NSDate *lastModif = [[[NSFileManager defaultManager] attributesOfItemAtPath:sourceFile error:&err] objectForKey:NSFileModificationDate];