问题
I am trying to develop an application (still learning) where i present a logon screen which takes a username and password - this then goes off to a web service to authenticate and returns an access token.
The access token is then stored in userdefaults and then presents a new view controller which gives access to the secured data.
My problem is that when i close my app - force close, it then asks to login again.
Because my login view controller is the initial view controller then i added a check to see if access token exists in userdefaults and present the new view controller which gives access to the secured data. Now my problem is that the login screen is always open behind my secured view controller so when opening the app from scratch you can briefly see the login view controller before it then presents the secured view controller.
How would i ideally handle this, is it the case the initial view controller is set to the secured view controller when the user defaults key exists - but doing this how would i handle the logout function as i would need to 'pop' to root view controller and clear user defaults, but since the login screen isnt in the view hierarchy then i cannot return to this? If it presented the login view controller on logout then the secured view controller still exists under the login view controller.
Sorry if this is a little long winded but just trying to describe the problem i am having.
Thanks
回答1:
You just need to in the Appdelegate.swift
's application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
method to judge.
But the precondition is you should manual operation the window:
Delete this line in your info.plist
:
Then in your AppDelegate.swift
you can set your window manually:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow.init(frame: UIScreen.main.bounds)
let sb:UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let isLogin:Bool = UserDefaults.standard.bool(forKey: "isLogin")
if isLogin {
let vc2 = sb.instantiateViewController(withIdentifier: "ViewController2")
self.window?.rootViewController = vc2
}else {
let vc1 = sb.instantiateViewController(withIdentifier: "ViewController")
self.window?.rootViewController = vc1
}
self.window?.makeKeyAndVisible()
return true
}
And in your ViewController.swift
(you can regard it as LoginVc):
override func viewDidLoad() {
super.viewDidLoad()
/* add userdefaults */
UserDefaults.standard.set(true, forKey: "isLogin")
UserDefaults.standard.synchronize()
}
来源:https://stackoverflow.com/questions/41864151/how-to-present-login-screen-only-when-a-userdefaults-key-doesnt-exist