我有一个登录视图控制器,用户需要键入用户名和密码才能看到主页。现在用户必须每次输入用户名和密码,这是不方便的。我需要有一个“记住用户名”和“记住密码”的复选框,以便用户可以选择是否希望他们下次登录时存储密码的用户名。Xcode:存储用户名和密码
任何好的方法来做到这一点?或者我必须使用钥匙扣,这是很多人认为最好的方法吗?
我的代码如下:
import UIKit
import Firebase
class LoginViewController: UIViewController {
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.image = #imageLiteral(resourceName: "background")
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubview(toBack: imageView)
activityIndicator.hidesWhenStopped = true
}
//Outlets
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
//Login Action
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBAction func loginAction(_ sender: AnyObject) {
self.activityIndicator.startAnimating()
if self.emailTextField.text == "" || self.passwordTextField.text == "" {
//Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in
let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
self.activityIndicator.stopAnimating()
} else {
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
if error == nil {
//Print into the console if successfully logged in
print("You have successfully logged in")
//Go to the HomeViewController if the login is sucessful
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
self.activityIndicator.stopAnimating()
} else {
//Tells the user that there is an error and then gets firebase to tell them the error
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
self.activityIndicator.stopAnimating()
}
}
}
}
}
尝试使用钥匙串其更安全的方式,请参阅https://medium.com/ios-os-x-development/securing-user-data-with-keychain-for-ios-e720e0f9a8e2 – Arun