嗨,我只想在第一次使用时显示视图控制器(即,第一次有人启动应用程序,并且再也不会启动)。
我认为我的代码正确,但由于某种原因,它无法正常工作。有人知道为什么吗?
AppDelegate.swift
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let userDefaults = UserDefaults.init()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
userDefaults.set(true, forKey: "isFirstTime")
userDefaults.set("RealmNotChosenOrSuggested", forKey: "RegionPreference")
userDefaults.set([], forKey: "PreferredRealms")
// Not using Storyboard instantiation code
window = UIWindow(frame:UIScreen.main.bounds) //canvas
window?.makeKeyAndVisible()
if (userDefaults.bool(forKey: "isFirstTime")){
userDefaults.set(false, forKey: "isFirstTime")
window?.rootViewController = StartupViewController()
} else{
window?.rootViewController = DashboardViewController()
}
return true
}
StartupViewController.swift
class StartupViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
DashboardViewController.swift
import UIKit
class DashboardViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .blue
}
答案 0 :(得分:2)
由于每次应用打开都会运行,因此您覆盖了第一行中的密钥isFirstTime
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// userDefaults.set(true, forKey: "isFirstTime") // firs line comment it
if !(userDefaults.bool(forKey: "isFirstTime")){
userDefaults.set(true, forKey: "isFirstTime")
userDefaults.set("RealmNotChosenOrSuggested", forKey: "RegionPreference")
userDefaults.set([], forKey: "PreferredRealms")
window?.rootViewController = StartupViewController()
} else{
window?.rootViewController = DashboardViewController()
}