我希望我第一次登录时会出现类似教程的内容。
但是它说:
二进制运算符'=='不能应用于类型为'String?'的操作数和“布尔”
override func viewDidLoad() {
super.viewDidLoad()
let checkForFirstTimeLaunch = UserDefaults.standard.string(forKey: "Flag")
if checkForFirstTimeLaunch == false {
print("First time launch")
//if user launches app for the first time, it will go here
let PageViewController = self.storyboard?.instantiateViewController(withIdentifier: "PageViewController") as! PageViewController
self.present(PageViewController, animated: true)
} else {
//otherwise, it will go here
let HomeViewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.present(HomeViewController, animated: true)
}
}
答案 0 :(得分:0)
使用此方法首次启动应用 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
}
}
答案 1 :(得分:0)
正如其他人所述,您只能比较String
-String
或Bool
-Bool
。在这种情况下-对于标志-最好使用Bool
此外,用户首次启动应用后,还必须保存true
。
override func viewDidLoad() {
super.viewDidLoad()
let checkForFirstTimeLaunch = UserDefaults.standard.bool(forKey: "Flag") // default is false
if checkForFirstTimeLaunch == false {
print("First time launch")
UserDefaults.standard.set(true, forKey: "Flag") // save `true` to go to the else branch the next time
//if user launches app for the first time, it will go here
let PageViewController = self.storyboard?.instantiateViewController(withIdentifier: "PageViewController") as! PageViewController
self.present(PageViewController, animated: true)
} else {
//otherwise, it will go here
let HomeViewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.present(HomeViewController, animated: true)
}
}
但是,从逻辑角度讲,默认情况下, FirstTimeLaunch 应该为 true
。在这种情况下,请在使用前注册键值对。在更改之前,将考虑已注册的默认值:
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
userDefaults.register(defaults: ["firstLaunch" : true])
let isFirstLaunch = userDefaults.bool(forKey: "firstLaunch")
if isFirstLaunch {
print("First time launch")
userDefaults.set(false, forKey: "firstLaunch") // save `false` to go to the else branch the next time
//if user launches app for the first time, it will go here
let PageViewController = self.storyboard?.instantiateViewController(withIdentifier: "PageViewController") as! PageViewController
self.present(PageViewController, animated: true)
} else {
//otherwise, it will go here
let HomeViewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.present(HomeViewController, animated: true)
}
}