Reputation: 4270
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.
Upvotes: 2
Views: 1994
Reputation: 3475
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")
}
Upvotes: 5
Reputation: 10492
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")
}
Upvotes: 4