AuthViewController.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseAuth
  15. import UIKit
  16. class AuthViewController: UIViewController {
  17. // MARK: - User Interface
  18. /// A stackview containing all of the buttons to providers (Email, OAuth, etc).
  19. @IBOutlet var providers: UIStackView!
  20. /// A stackview containing a signed in label and sign out button.
  21. @IBOutlet var signedIn: UIStackView!
  22. /// A label to display the status for the signed in user.
  23. @IBOutlet var signInStatus: UILabel!
  24. // MARK: - User Actions
  25. @IBAction func signOutButtonHit(_ sender: UIButton) {
  26. // Sign out via Auth and update the UI.
  27. try? Auth.auth().signOut()
  28. setUserSignedIn(nil)
  29. }
  30. // MARK: - View Controller Lifecycle
  31. override func viewDidLoad() {
  32. super.viewDidLoad()
  33. // Update the UI based on the current user (if there is one).
  34. setUserSignedIn(Auth.auth().currentUser)
  35. }
  36. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  37. let destination = segue.destination
  38. if let emailVC = destination as? EmailLoginViewController {
  39. emailVC.delegate = self
  40. }
  41. }
  42. // MARK: - Internal Helpers
  43. private func setUserSignedIn(_ user: User?) {
  44. if let user {
  45. providers.isHidden = true
  46. signedIn.isHidden = false
  47. signInStatus.text = "User is signed in via \(user.providerID) and the UID \(user.uid)"
  48. } else {
  49. // User is signed out, hide the signed in state and show the providers.
  50. providers.isHidden = false
  51. signedIn.isHidden = true
  52. }
  53. }
  54. }
  55. // MARK: - EmailLoginDelegate conformance.
  56. extension AuthViewController: EmailLoginDelegate {
  57. func emailLogin(_ controller: EmailLoginViewController, signedInAs user: User) {
  58. setUserSignedIn(user)
  59. dismiss(animated: true)
  60. }
  61. func emailLogin(_ controller: EmailLoginViewController, failedWithError error: Error) {
  62. print("Fail..... \(error)")
  63. DispatchQueue.main.async {
  64. controller.presentError(with: "There was an issue logging in. Please try again.")
  65. }
  66. }
  67. }