Xcode: Store Username and Password - ios

I have a login view controller that users need to type username and password in order to see the homepage. Now the users must type in the username and password every single time, which isn't convenient. I need to have a check box for "remember username" and "remember password" so that users can choose wether or not they would like to have their username of password stored the next time they login.
Any good way to do that? Or do I have to use Keychain, which according to many people is the best way?
My code is as follows:
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()
}
}
}
}
}

Below are some ways in which you can stored your credential:
NSUserDefault
plist
KeyChain Store
Local Database (SQLite)
CoreData
From above all, NSUserDefault and Keychain are best and easy way to use.
NSUserDefault:
For Storing into Default:
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
Getting from Defaults:
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Key")
UserDefaults.standard.string(forKey: "Key")
KeyChain: . Checkout this demo for keychain.

You can use any one of the below approach -
NSUserDefaults
KeychainWrapper
NSURLCredential
Reference URL iOS: How to store username/password within an app?

Keychain is the most secure place to store the raw password.It means better than any other places.
You can use KeychainWrapper which is providing from Appleā€™s Keychain Services Programming Guide.

Related

Alerts Not Showing Up On Phone Screen when Testing App

I am currently working on a social media app and so far I have been able to make a LoginViewController & a SignUpVIewController, and have it where when the user taps on the Sihn Up Button on the LoginViewController it takes them to the SignUpViewCOntroller. Right now I am currently trying to have it where on the SignUpViewController if not all required fields are filled out then the app will display an alert. However, every time I run the app the alert doesn't show up on the simulator screen.
My code for the SignUpViewController is as follows:
import UIKit
import Parse
class SignUpViewController: UIViewController
{
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var usernameTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var confirmPasswordFieldText: UITextField!
#IBOutlet weak var signUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func signUpButtonTapped(_ sender: UIButton)
{
let username = usernameTextField.text
let password = passwordTextField.text
let email = emailTextField.text
let confirmpw = confirmPasswordFieldText.text
if username == "" || password == "" || email == "" || confirmpw == ""
{
let alert = UIAlertController(title: "Error", message: "Please fill out all required fields", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default,handler: nil))
present(alert, animated: true, completion: nil)
return
}
let newUser = User(username: username!, password: password!, email: email!)
}
}
class User
{
var username: String
var password: String
var email: String
init(username: String, password: String, email: String) {
self.username = username
self.password = password
self.email = email
}
}
Essentially when I tap the SignUp button on my SignUpViewController while leaving all the fields blank it still takes me to the next view controller (which I plan to have been the profile creation view controller), instead of showing the alerts. All the buttons are connected to the correct spots. Would greatly appreciate it if anyone can help me fix this.
It appears (I'm making an assumption here but without a screenshot of your storyboard it is hard to be certain) you may have connected the button in your storyboard to the next view controller via a segue. If that's the case then it would automatically move to the next view controller. So, here you should remove your segue inside the storyboard and programatically navigate to the next screen using your #IBAction method.
Also, unrelated to this, but #INFINITE's comment is also a good observation. You should probably use a guard statement here like below:
#IBAction func signUpButtonTapped(_ sender: UIButton) {
guard let username = usernameTextField.text,
let password = passwordTextField.text,
let email = emailTextField.text,
let confirmpw = confirmPasswordFieldText.text else {
// It may be a good idea to refactor this bit into a separate method
let alert = UIAlertController(title: "Error", message: "Please fill out all required fields", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
}
let newUser = User(username: username, password: password, email: email)
// present the next view controller here
let storyboardInstance = UIStoryboard.init(name: "YOUR_STORYBOARD_NAME", bundle: Bundle.main)
if let profileViewController = storyboardInstance.instantiateViewController(withIdentifier: "YOUR_VIEWCONTROLLER_STORYBOARD_ID") {
// set whatever your have to on the profile view controller here
// profileViewController.user = newUser
// then,
// either push the next view controller
// navigationViewController?.pushViewController(profileViewController, animated: true)
// or present it
// present(profileViewController, animated: true)
// or do whatever else is needed
}
}

Why won't my swift code process firebase email authentication?

I have view controllers connected with my code that include a login page and a sign up page, I've started a firebase project and connected with my Xcode and it successfully connected to the firebase servers. The code below is for my sign up view controller and is supposed to act like a sign up form with email, password and password confirmation but for some reason the build succeeds with no errors but the user that registered does not show up on my firebase user database and the textfields don't act like the way they should (i.e throw an error if password and password confirmation don't match) .
import UIKit
import FirebaseAuth
import FirebaseCore
import Firebase
class SignUpViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func SignUpToHome(sender: AnyObject) {
performSegue(withIdentifier: "SignUpToHome", sender: sender)
}
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var passwordConfirm: UITextField!
#IBAction func signUpAction(_ sender: Any) {
//func signUpAction(_ sender: Any) {
//}
if password.text != passwordConfirm.text {
let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
else{
Auth.auth().createUser(withEmail: email.text!, password: password.text!){ (user, error) in
if error == nil {
self.performSegue(withIdentifier: "SignUpToHome", sender: self)
}
else{
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)
}
}
}
}
}

Error - The email address is badly formed. Xcode Swift Firebase

I'm building a UI interface with authentication as an iOS app. I've come a long way from where I was originally but I cannot get past this error. I don't understand what I'm compiling incorrectly. Please take a look and help me out if you can.
import UIKit
import Firebase
class SignUpViewController: UIViewController, UITextFieldDelegate
{
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var passwordConfirm: UITextField!
#IBOutlet weak var signUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
email.delegate = self
password.delegate = self
passwordConfirm.delegate = self
}
#IBAction func signUpAction(_ sender: UIButton) {
if password.text !=
passwordConfirm.text{
let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
else{
Auth.auth().createUser(withEmail: email.text!, password: password.text!){ (user, error) in
if error == nil {
self.performSegue(withIdentifier: "signupToHome", sender: self)
}
else{
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)
}
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
}
The goal is to then accept the user input from email.text and password.text and segue into the home screen after creating a new user in my Firebase console.
Firebase has its own email validation which is like this 'abc#somedomain.com' so you need to pass a email address like this other wise it will keep throwing this error.

Xcode 8.3.3: How to Remember Username and Password and Add Touch-ID Authentication

My current project has a login page, but I find that the user must enter their username and password again when they log in. How do I make it easier for them, by implementing "remember username and password" functionality and adding Touch ID?
My code is as follows:
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)
}
//Outlets
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
//Login Action
#IBAction func loginAction(_ sender: AnyObject) {
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)
} 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)
} 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)
}
}
}
}
you have a couple of ways to save your user Credentials. Most common way is to save those in Keychain.
KeyChain Swift
After that you can user your touchID authentication, by calling the default methods to implement this. Here is a nice tutorial how you should do it:
Touch ID for Local Authentication

Adding Activity Indicator after Clicking "LOGIN"?

I would like to add an Activity Indicator for my Login VC so that users will see that spinner thing once they click the "login" button. I have done multiple attempts and failed. Even if I put in codes for hiding the activity indicator, it just keeps animating even before clicking the "login" button. I deleted those codes, and have my original codes below (without activity indicator).
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)
}
//Outlets
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
//Login Action
#IBAction func loginAction(_ sender: AnyObject) {
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)
} 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)
} 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)
}
}
}
}
so I know the first step is probably dragging the activity indicator to the VC in Storyboard, but what's next?
You need to create a IBOutlet of dragged UIActivityIndicator. Then in viewDidLoadfunc hide this UIActivityIndicator with it's IBOutlet. When you click on Login Button, then unhide this activityIndicator and hide again, once receive response from login.
Create an IBOUtlet of your activity indicator from Storyboard to your Viewcontroller -
You can then in your ViewDidLoad or your storyboard set the below property
activityIndicator.hidesWhenStopped = true;
And when you want to start it, call
activityIndicator.startAnimating();
And to stop it from animating -
activityIndicator.stopAnimating();
The same way you created your IBOutlets of UITextField, create one with your UIActivityIndicator. Make sure your indicator's hidesWhenStopped is set to true in the storyboard.
Then animate it before calling your signin method, and stop it on the completion handler
#IBOutlet weak var activityIndicator: UIActivityIndicator!
//...
activityIndicator.startAnimating()
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in {
activityIndicator.stopAnimating()
//...
}
You can create UIActivityIndicatorView in your class programmatically & customize it in viewDidLoad
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
// Add below code in viewDidLoad
self.activityIndicator.hidesWhenStopped = true
self.activityIndicator.center = view.center
self.view.addSubView(self.activityIndicator)
Now do start & stop animating whereever you need
//Login Action
#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)
} else {
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
self.activityIndicator.stopAnimating()
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)
} 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)
}
}
}
In your storyboard, you can find checkbox.
startsAnimating
HidesWhenStops(check this in your storyboard.)
#IBOutlet weak var activityIndicator: UIActivityIndicator!
#IBAction func loginAction(_ sender: AnyObject) {
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)
activityIndicator.stopAnimating()
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} 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")
activityIndicator.stopAnimating()
//Go to the HomeViewController if the login is sucessful
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
} 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)
}
}
}
}
An alternative Approach. Adding the UIActivityViewController programatically:
In the LoginViewController class add
let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
In the viewDidLoad() add the following
myActivityIndicator.hidesWhenStopped = true
myActivityIndicator.center = view.center
view.addSubview(myActivityIndicator)
In #IBAction func loginAction(_ sender: AnyObject) in the else part
add
activityIndicator.startAnimating()
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in {
activityIndicator.stopAnimating()
I have written a class to use progress hud properly. You just need to drag and drop the class to your project...
https://github.com/emraz/ERProgressHud
For showing progress hud write ..
ERProgressHud.show()
For hiding progress hud write ..
ERProgressHud.hide()
In your code ..
//Login Action
#IBAction func loginAction(_ sender: AnyObject) {
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)
return
}
else {
ERProgressHud.show()
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
ERProgressHud.hide()
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)
} 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)
}
}
}
}

Resources