Search code examples
iosswiftalamofire

How to show alert for a specific server status code in swift 3?


I built an app which lets users login to the server and it works fine. Now I want to show an error alert saying that something is wrong when server returns statusCode: 500. Also I want to prevent the segue so it stays at the login screen until the user enters correct credentials.

Here is my class:

    import Alamofire //A framework for handling http requests nicely
    import UIKit 

 //A class which will do the login process
  class InitialViewController: UIViewController {

//Variables for the URL, parameters, authentication token and alertView
let url = "https://api.sis.kemoke.net/auth/login"
var parameters = ["email": "", "password": ""]
var token = ["X-Auth-Token": ""]

// Parameters textfields
@IBOutlet weak var email: UITextField?
@IBOutlet weak var password: UITextField?

// A method for the login button
@IBAction func loginButton(_ sender: UIButton) {
    parameters["email"] = email?.text //Read email from text field
    parameters["password"] = password?.text //Read password from text field
    Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: token).responseJSON {
        (response) in
        print(response.result.value as Any)
        //Reading JWT authentication token from the server
                    if let tokenString = response.result.value as? String {
            self.token["X-Auth-Token"] = tokenString
        }
        //Check if the server returned nil
        if response == nil {
        let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
         alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
         self.present(alert, animated: true, completion: nil)
        }


        //Show the error message

        //Check NSUserData if the user is already logged in
    }
}
//ViewDidLoad method used to preconfigure the first view
override func viewDidLoad() {
    super.viewDidLoad()
}
 }

Solution

  • I can help you with neat & alternative answer if you can provide demo response for successful login attempt.

    Replace this code in your loginButton method:

    @IBAction func loginButton(_ sender: UIButton) {
        parameters["email"] = email?.text //Read email from text field
        parameters["password"] = password?.text //Read password from text field
        Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: token).responseJSON {
            (response) in
    
            //Reading JWT authentication token from the server
            if let tokenString = response.result.value as? String {
                self.token["X-Auth-Token"] = tokenString
            }
    
            //Check if the server returned nil
            let responseObject = response.result.value as! Dictionary<String, Any>
            let statusCode = responseObject["statusCode"] as! Int
            print("Status Code \(statusCode)")
    
            // manage alerts for different status codes
            if statusCode == 500 {
                // present alert
                let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            } else if  statusCode == 200 {
                // 200 status code for successful login
                // code to navigate to other screen
                // depends on what reponse you are getting on successful login attempt
            }
        }
    }