ios8

Run a snippet of code only once in lifetime for a app - Swift -Xcode

by
published on
I have to do a Core data initialization where i have to put a chunk of sample data inside Core Data only once when the app has been opened for the first time. Here is a simple code snippet in swift for IOS8 which has helped me to do.
        if(!NSUserDefaults.standardUserDefaults().boolForKey("firstlaunch1.0")){
            //Put any code here and it will be executed only once.
            println("Is a first launch")
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "firstlaunch1.0")
            NSUserDefaults.standardUserDefaults().synchronize();
        }
Code explanation. Here i am checking that if i have any boolean called as firstlaunch1.0 has been set to true before in the user default database. If not then execute the code and set the boolean to TRUE. Trick: Now if you see i have kept the flag name with a 1.0 assigned to it. Say in future you want to run this code snippet again for all users because of some code update all you need to do is just change the version number of the flag and send an app update. The snippet will run again.