简体   繁体   中英

Is there a function in Swift that only runs during the first time opening the app?

I'm currently making a dictionary app and I'm re-parsing through the json file that contains all the entries of the dictionaries every time I open the app and saving it to CoreData. I was wondering if there is a function in Swift that just runs once when the app is downloaded and then doesn't run again.

What you can do set a NSUserDefaults to check whether it is a first run or not:

let firstRun = NSUserDefaults.standardUserDefaults().boolForKey("firstRun") as Bool
if !firstRun {
    //run your function
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "firstRun")
}

Swift 4 example:

In your ViewController

let firstRun = UserDefaults.standard.bool(forKey: "firstRun") as Bool

Then in your viewDidLoad

if firstRun {
    //function you want to run normally
} else {
    runFirst() //will only run once
}

Then make this function down below

func runFirst() {
    print("FIRST RUN!")
    UserDefaults.standard.set(true, forKey: "firstRun")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM