Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- // ---- [LoginManager.swift] ---- starts
- enum LoginError: Error {
- case minUserNameLength(String), minPasswordLength(String), invalidUserName(String), invalidPassword(String)
- }
- enum LoginResult {
- case result([String: Any])
- }
- struct LoginManager {
- static func validate(user: String, pass: String, completion: (LoginResult) -> Void ) throws {
- guard (!user.isEmpty && user.count > 8) else { throw LoginError.minUserNameLength("A minimum username length is >= 8 characters.") }
- guard (!pass.isEmpty && pass.count > 8) else { throw LoginError.minPasswordLength("A minimum password length is >= 8 characters.") }
- //Call Login API to confirm the credentials with provided userName and password values.
- //Here we're checking locally for testing purpose.
- if user != "iosdevfromthenorthpole" { throw LoginError.invalidUserName("Invalid Username.") }
- if pass != "polardbear" { throw LoginError.invalidPassword("Invalid Password.") }
- //The actual result will be passed instead of below static result.
- completion(LoginResult.result(["userId": 1, "email": "nointernet@thenorthpole.com"]))
- }
- static func handle(error: LoginError, completion: (_ title: String, _ message: String) -> Void) {
- //Note that all associated values are of the same type for the LoginError cases.
- //Can we write it in more appropriate way?
- let title = "Login failed."
- switch error {
- case .minUserNameLength(let errorMessage):
- completion(title, errorMessage)
- case .minPasswordLength(let errorMessage):
- completion(title, errorMessage)
- case .invalidUserName(let errorMessage):
- completion(title, errorMessage)
- case .invalidPassword(let errorMessage):
- completion(title, errorMessage)
- }
- }
- }
- // ---- [LoginManager.swift] ---- ends
- // ---- [LoginViewController.swift] ---- starts
- //Confirming the user credentials when user taps on the "Login" button.
- do {
- try LoginManager.validate(user: "iosdevfromthenorthpole", pass: "polardbear", completion: { (loginResult) in
- switch loginResult {
- case .result (let result):
- print("userId: ", result["userId"] ?? "Not available.")
- print("email: ", result["email"] ?? "Not available.")
- }
- })
- } catch let error as LoginError {
- LoginManager.handle(error: error) { (title, message) in
- //Show an alert with title and message to the user.
- print(title + " " + message)
- }
- }
- // ---- [LoginViewController.swift] ---- ends
Add Comment
Please, Sign In to add comment