Skip to content

Instantly share code, notes, and snippets.

@charleshkang
Created April 14, 2016 07:52
Show Gist options
  • Save charleshkang/53ae392f40410dee862af4b25c7372bb to your computer and use it in GitHub Desktop.
Save charleshkang/53ae392f40410dee862af4b25c7372bb to your computer and use it in GitHub Desktop.
//
// LoginViewController.swift
// FirebaseJokes
//
// Created by Matthew Maher on 1/23/16.
// Copyright © 2016 Matt Maher. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// If we have the uid stored, the user is already logger in - no need to sign in again!
if NSUserDefaults.standardUserDefaults().valueForKey("uid") != nil && DataService.dataService.CURRENT_USER_REF.authData != nil {
self.performSegueWithIdentifier("CurrentlyLoggedIn", sender: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func tryLogin(sender: AnyObject) {
let email = emailField.text
let password = passwordField.text
if email != "" && password != "" {
// Login with the Firebase's authUser method
DataService.dataService.BASE_REF.authUser(email, password: password, withCompletionBlock: { error, authData in
if error != nil {
print(error)
self.loginErrorAlert("Oops!", message: "Check your username and password.")
} else {
// Be sure the correct uid is stored.
NSUserDefaults.standardUserDefaults().setValue(authData.uid, forKey: "uid")
// Enter the app!
self.performSegueWithIdentifier("CurrentlyLoggedIn", sender: nil)
}
})
} else {
// There was a problem
loginErrorAlert("Oops!", message: "Don't forget to enter your email and password.")
}
}
func loginErrorAlert(title: String, message: String) {
// Called upon login error to let the user know login didn't work.
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment