Is there any way by which I can run a function only once (when the app is updated or installed)?
I can't use run script as I should use an Objective-C function.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ( ![userDefaults valueForKey:@"version"] )
{
// CALL your Function;
// Adding version number to NSUserDefaults for first version:
[userDefaults setFloat:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] forKey:@"version"];
}
if ([[NSUserDefaults standardUserDefaults] floatForKey:@"version"] == [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] )
{
// Same Version so dont run the function
}
else
{
// Call Your Function;
// Update version number to NSUserDefaults for other versions:
[userDefaults setFloat:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] forKey:@"version"];
}
This is the Swift conversion of Bhupendra's answer:
let infoDictionary: NSDictionary? = NSBundle.mainBundle().infoDictionary // Fetch info.plist as a Dictionary
let temp: NSString = infoDictionary?.objectForKey("CFBundleVersion") as NSString
let val: Float = temp.floatValue
var userDefaults = NSUserDefaults()
if userDefaults.valueForKey("version") == nil {
// Call function
// Adding version number to NSUserDefaults for first version
userDefaults.setFloat(val, forKey: "version")
}
if NSUserDefaults().floatForKey("version") == val {
// Same Version so dont run the function
} else {
// Call function
// Update version number to NSUserDefaults for other versions
userDefaults.setFloat(val, forKey: "version")
}
If you want to run some code when the app is either first installed or after every update then you could read the current version of your application from your bundle
CGFloat currentVersion = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue];
and write that to user defaults after you have run the code.
[[NSUserDefaults standardUserDefaults] setFloat:currentVersion
forKey:kLastVersionThatExecutedMyCodeKey];
The next time you start your app, you compare the value from the user defaults against the bundle version. If the bundle version has changed the app was updated which means that you should run the code again and write the new version to user defaults.
You can create a BOOL value key (e.g. isFirstLaunch = NO
) in your NSUserDefaults
, and set it to YES after you've executed the function.
If you want to execute it every time the user launch the App, you'll need to set the key to default value before the App exists (i.e. reset it in -applicationWillTerminate:
method in AppDelegate).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With