我需要设置和存储一些可用于视图的 NSUserDefaults 数据。这不适用于 viewDidLoad。
这可以做到吗?在 viewDidLoad 之前我可以使用什么方法?你会推荐什么?
我需要设置和存储一些可用于视图的 NSUserDefaults 数据。这不适用于 viewDidLoad。
这可以做到吗?在 viewDidLoad 之前我可以使用什么方法?你会推荐什么?
有几种方法UIViewController
肯定会在之前运行viewDidLoad
- 这是您的代码的合适位置取决于您的特定问题和体系结构。
initWithNibName:bundle:
在创建视图控制器时调用loadView
是设置视图的代码另一种选择是确保在视图控制器初始化之前由不同的组件设置默认值。这可能在工作流前一部分的视图控制器中,或者由应用程序委托初始化。
applicationDidFinishLaunching 听起来像是默认设置的好地方
在您的应用程序的 AppDelegate 中尝试
这是一个使用 UserDefaults 保持应用程序登录状态的示例:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// You can keep your Google API keys here(if you have any)
let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
let homeScreen = storyBoard.instantiateViewController(withIdentifier: "YourHomecontroller") as? ViewController
if(UserDefaults.standard.isLoggedIn()){
self.window?.rootViewController = homeScreen
}else{
let loginScreen = storyBoard.instantiateViewController(withIdentifier: "LoginViewController")
self.window?.rootViewController = loginScreen
}
return true
}
并使用以下方法扩展 UserDefaults:
// this is used to serialize the boolean value:isLoggedIn
func setIsLoggedIn(value:Bool){
setValue(value, forKey: "isLoggedIn")
UserDefaults.standard.synchronize()
}
// this method is used to check the value for isLoggedIn flag
func isLoggedIn() -> Bool{
return bool(forKey: "isLoggedIn")
}
这样,您可以有条件地在视图控制器之间切换。如果用户已经通过身份验证,您将希望显示主屏幕。