Search code examples
swiftalamofireswift5

How to set an identifier for 'error' in alamofire for login page


I am trying to set an error identifier so a user gets an error message in a errorLabel if the info they typed in is wrong. I tried to put 'error' in { (response) in but that threw errors. What is a good way to handle this.

AF.request(url, method: .post, parameters: parameters as Parameters, encoding: URLEncoding.default).response { (response) in

            print(response)

           if  error != nil {
               // Couldn't sign in
               self.errorLabel.text = error!.localizedDescription
               self.errorLabel.alpha = 1
           }
           else {

               let tabBarController =
                   self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.TabBarController) as? UITabBarController

               self.view.window?.rootViewController = tabBarController
               self.view.window?.makeKeyAndVisible()
            }
          }
        }

Solution

  • You can identify error using switch case in alamofire.

    AF.request(url, method: .post, parameters: parameters as Parameters, encoding: 
    URLEncoding.default).response { (response) in
    
            switch response.result {
                 case .success:
                 //sign in
                 let tabBarController =
                 self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.TabBarController) as? UITabBarController
                 self.view.window?.rootViewController = tabBarController
                 self.view.window?.makeKeyAndVisible()
    
                 case .failure(let error):
                 // Couldn't sign in
                 self.errorLabel.text = error!.localizedDescription
                 self.errorLabel.alpha = 1
            }
          }