简体   繁体   English

Swift 中是否有仅在第一次打开应用程序时运行的功能?

[英]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.

相关问题 从扩展程序打开应用程序,属性仅在第一次更改 - Opening app from extension, properties only change the first time Swift:首次运行应用程序时,如何将文件从应用程序包复制到“文档”文件夹 - Swift: How to copy files from app bundle to Documents folder when app runs for first time 如何在应用程序第一次运行时在我的iOS应用程序中打开页面视图控制器? - How to open a page view controller in my iOS app only the first time the app runs? 如何确定用户第一次运行应用程序? - How to determine that user runs the app for the first time? 首次打开应用程序时显示UIScrollView - Present a UIScrollView when opening an App for the first time 仅在第一个应用程序打开时显示教程视图 - Show Tutorial View on First App Opening Only NSTimer仅在第一次工作(快速) - NSTimer work only the first time (Swift) 如何使视图控制器仅在用户第一次快速打开应用程序时出现 - How to make a view controller only appear the first time a user opens the app in swift 第一次进入App时,使用UIPageViewController快速完成教程页面的首选方法是 - Which is the preferred way of doing tutorial page with UIPageViewController in swift for first time entering App only Swift NSUserDefaults应用首次崩溃 - Swift NSUserDefaults app crash first time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM