import Foundation
import SwiftyUserDefaults
// Define app user defaults keys
extension DefaultsKeys {
var isFirstAppLaunch: DefaultsKey<Bool> { .init("isFirstAppLaunch", defaultValue: true) }
}
接下来,在您的视图控制器ViewDidload中您可以实现以下操作:
import SwiftyUserDefaults
override func viewDidLoad() {
super.viewDidLoad()
self.fillDataInFirstAppLaunch()
}
func fillDataInFirstAppLaunch() {
// If first execution, then fill CoreData with default values
if Defaults.isFirstAppLaunch {
// Set to false to run this code only once (the first app launch)
Defaults.isFirstAppLaunch = false
// Implement your logic here to fill CoreData
}
}
Well one of the things that I normally do to know if my application is running for the first time is to store a value in User Defaults. You can also store the number of executions your application has had and then implement your logic based on this value. Here I leave you as I would.
To work with the User Defaults I use this library that is great: SwiftyUserDefaults
Create a file named (for example)
UserDefaults.swift
Inside this file put this code:
import Foundation
import SwiftyUserDefaults
// Define app user defaults keys
extension DefaultsKeys {
var isFirstAppLaunch: DefaultsKey<Bool> { .init("isFirstAppLaunch", defaultValue: true) }
}
Next, in your view controller viewDidLoad you can implement this:
import SwiftyUserDefaults
override func viewDidLoad() {
super.viewDidLoad()
self.fillDataInFirstAppLaunch()
}
func fillDataInFirstAppLaunch() {
// If first execution, then fill CoreData with default values
if Defaults.isFirstAppLaunch {
// Set to false to run this code only once (the first app launch)
Defaults.isFirstAppLaunch = false
// Implement your logic here to fill CoreData
}
}
发布评论
评论(1)
好吧,我通常要知道我的应用程序是否首次运行的一件事是在用户默认值中存储一个值。您还可以存储应用程序已有的执行次数,然后根据此值实现逻辑。在这里,我像我一样离开你。
要与用户默认工作,我使用的是很棒的库:
swiftyuserdefaults )
此文件中的swift放置此代码:
接下来,在您的视图控制器ViewDidload中您可以实现以下操作:
Well one of the things that I normally do to know if my application is running for the first time is to store a value in User Defaults. You can also store the number of executions your application has had and then implement your logic based on this value. Here I leave you as I would.
To work with the User Defaults I use this library that is great: SwiftyUserDefaults
Create a file named (for example)
Inside this file put this code:
Next, in your view controller viewDidLoad you can implement this: