我希望在用户首次打开我的应用时显示欢迎屏幕。有什么方法可以检查Swift中第一次启动应用程序?
答案 0 :(得分:16)
class Blog
def has_title?
title.present?
end
end
注意:此方法会在用户重新安装应用并首次启动后返回func isAppAlreadyLaunchedOnce()->Bool{
let defaults = UserDefaults.standard
if let _ = defaults.string(forKey: "isAppAlreadyLaunchedOnce"){
print("App already launched")
return true
}else{
defaults.set(true, forKey: "isAppAlreadyLaunchedOnce")
print("App launched first time")
return false
}
}
。
答案 1 :(得分:14)
试试这个,
func isAppAlreadyLaunchedOnce()->Bool{
let defaults = NSUserDefaults.standardUserDefaults()
if let isAppAlreadyLaunchedOnce = defaults.stringForKey("isAppAlreadyLaunchedOnce"){
println("App already launched")
return true
}else{
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
println("App launched first time")
return false
}
}
答案 2 :(得分:9)
由于在卸载应用程序时会删除应用程序的NSUserDefaults,因此您可以尝试在应用程序启动时测试是否存在某个值。
如果该值存在,则已安装该应用。如果没有,这是第一次启动应用程序,并设置该值。
答案 3 :(得分:1)
SWIFT:
let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
if launchedBefore {
print("Not first launch.")
} else {
print("First launch, setting UserDefault.")
UserDefaults.standard.set(true, forKey: "launchedBefore")
}
目标-C:
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isAppAlreadyLaunchedOnce"])
{
return true;
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isAppAlreadyLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
return false;
}
答案 4 :(得分:1)
由于我的应用中针对苹果bugs的某些data protection政策,我经常发现userDefault
无法访问,因此我更改了策略以检测到以下情况首次启动
if ( fileExists( dummyFilePath ) == NO ) {
createFileAt( dummyFilePath )
// This is first launch
}
答案 5 :(得分:0)
Objective-C 版本:
BOOL isAppLaunched = [[NSUserDefaults standardUserDefaults] boolForKey:@"launchedBefore"];
if (isAppLaunched) {
NSLog(@"Not first launch.");
}
else {
NSLog(@"First launch, setting NSUserDefault.");
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"launchedBefore"];
}
答案 6 :(得分:0)
对Jonas Deichelmann's答案进行了语义上的细微修改,以澄清一些事情:
打印语句清楚地表明,此功能只是在验证自上次安装以来是否已运行,而不是在此设备上是否曾经运行过。
func establishUserDefaultsHaveBeenVerifed()->Bool{
let defaults = UserDefaults.standard
if let _ = defaults.string(forKey: "userDefaultsHaveBeenVerified"){
print("user defaults were already verified")
return true
}else{
defaults.set(true, forKey: "userDefaultsHaveBeenVerified")
print("verified user defaults for first time since app was installed")
return false
}
}
答案 7 :(得分:0)
Swift 5
let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
if launchedBefore {
// Code if has launched before
} else {
UserDefaults.standard.set(true, forKey: "launchedBefore")
// Code if not has launched before
}