[英]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.我目前正在制作一个字典应用程序,每次打开应用程序并将其保存到 CoreData 时,我都会重新解析包含字典所有条目的 json 文件。 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.我想知道 Swift 中是否有一个函数在下载应用程序时只运行一次然后不再运行。
What you can do set a NSUserDefaults to check whether it is a first run or not:你可以设置一个 NSUserDefaults 来检查它是否是第一次运行:
let firstRun = NSUserDefaults.standardUserDefaults().boolForKey("firstRun") as Bool
if !firstRun {
//run your function
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "firstRun")
}
Swift 4 example:斯威夫特 4 示例:
In your ViewController在您的视图控制器中
let firstRun = UserDefaults.standard.bool(forKey: "firstRun") as Bool
Then in your viewDidLoad然后在你的 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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.