简体   繁体   English

在iOS应用中保留数据

[英]Persisting data in iOS app

I am new to iOS. 我是iOS新手。 I want to save authentication token recieved from a REST API to use in further api calls without requiring a login. 我想保存从REST API收到的authentication token ,以在以后的api调用中使用,而无需登录。 Currently I am using UserDefaults to store this token. 目前,我正在使用UserDefaults存储此令牌。 This token works fine unless app is completely closed. 除非应用程序完全关闭,否则此令牌可以正常工作。 Relaunching the app again takes me to login screen. 再次重新启动该应用程序使我进入登录屏幕。

Saving the token like this 这样保存token

UserDefaults.standard.setValue(authToken, forKey: "auth_token")
UserDefaults.standard.synchronize() // Now this call is derpecated. Framework handles this call at proper places.

LoginViewController LoginViewController

override func viewDidLoad(){
   super.viewDidLoad()

   if UserDefaults.standard.string(forKey: "auth_token") != nil { 
        self.performSegue(withIdentifier: "login_success", sender: self)
   }
}

But the issue is how can I persist this token even after the app was completely closed ? 但是问题是,即使应用程序完全关闭,我如何仍可以保留此令牌?

EDIT 编辑

I have also tried syncing UserDefaults within applicationWillTerminate methods of AppDelegate class just to make sure but that even doesn't work. 我也尝试过在AppDelegate类的applicationWillTerminate方法内同步UserDefaults ,只是为了确保但甚至不起作用。

Nothing wrong with the UserDefaults. UserDefaults没问题。 Just wrapping the triggering segue call in main queue was required to properly work. 仅需要将触发的segue调用包装在主队列中才能正常工作。

override func viewDidLoad() {
     super.viewDidLoad()

     if UserDefaults.standard.string(forKey: "auth_token") != nil {
       DispatchQueue.main.async {
         self.performSegue(withIdentifier: "login_success", sender: self)
       }
     }          
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM