Guest User

Untitled

a guest
Dec 24th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import UIKit
  2.  
  3. // ---- [LoginManager.swift] ---- starts
  4. enum LoginError: Error {
  5. case minUserNameLength(String), minPasswordLength(String), invalidUserName(String), invalidPassword(String)
  6. }
  7.  
  8. enum LoginResult {
  9. case result([String: Any])
  10. }
  11.  
  12. struct LoginManager {
  13. static func validate(user: String, pass: String, completion: (LoginResult) -> Void ) throws {
  14. guard (!user.isEmpty && user.count > 8) else { throw LoginError.minUserNameLength("A minimum username length is >= 8 characters.") }
  15. guard (!pass.isEmpty && pass.count > 8) else { throw LoginError.minPasswordLength("A minimum password length is >= 8 characters.") }
  16.  
  17. //Call Login API to confirm the credentials with provided userName and password values.
  18. //Here we're checking locally for testing purpose.
  19. if user != "iosdevfromthenorthpole" { throw LoginError.invalidUserName("Invalid Username.") }
  20. if pass != "polardbear" { throw LoginError.invalidPassword("Invalid Password.") }
  21.  
  22. //The actual result will be passed instead of below static result.
  23. completion(LoginResult.result(["userId": 1, "email": "nointernet@thenorthpole.com"]))
  24. }
  25.  
  26. static func handle(error: LoginError, completion: (_ title: String, _ message: String) -> Void) {
  27. //Note that all associated values are of the same type for the LoginError cases.
  28. //Can we write it in more appropriate way?
  29. let title = "Login failed."
  30. switch error {
  31. case .minUserNameLength(let errorMessage):
  32. completion(title, errorMessage)
  33. case .minPasswordLength(let errorMessage):
  34. completion(title, errorMessage)
  35. case .invalidUserName(let errorMessage):
  36. completion(title, errorMessage)
  37. case .invalidPassword(let errorMessage):
  38. completion(title, errorMessage)
  39. }
  40. }
  41. }
  42. // ---- [LoginManager.swift] ---- ends
  43.  
  44. // ---- [LoginViewController.swift] ---- starts
  45. //Confirming the user credentials when user taps on the "Login" button.
  46.  
  47. do {
  48. try LoginManager.validate(user: "iosdevfromthenorthpole", pass: "polardbear", completion: { (loginResult) in
  49. switch loginResult {
  50. case .result (let result):
  51. print("userId: ", result["userId"] ?? "Not available.")
  52. print("email: ", result["email"] ?? "Not available.")
  53. }
  54. })
  55. } catch let error as LoginError {
  56. LoginManager.handle(error: error) { (title, message) in
  57. //Show an alert with title and message to the user.
  58. print(title + " " + message)
  59. }
  60. }
  61. // ---- [LoginViewController.swift] ---- ends
Add Comment
Please, Sign In to add comment