Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Authentication with POST request is failing to validate data

So I have a created a POST request which validates the Username and Password when someone tries to login, The problem is when i press the button sender it doesn’t validate the data at all even if the Username and Password field are empty it still segues you to the main Dashboard which I find it very weird.

The Button Sender from signInViewController class :

@IBAction func signInSegueToDashboard(_ sender: Any) {
    
    APICallerPOST.shared.signInToAccount(username: emailFieldSignIn.text!, password: passwordFieldSignIn.text!) { [self] (result, error) in
        
        switch result?.StatusCode {
        case 0:
            DispatchQueue.main.async {
                
                activityLoaderSignIn.startAnimating()
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                
                guard let mainTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "mainTabBarController")
                else {
                    return
                }
                
                self.activityLoaderSignIn.stopAnimating()
                mainTabBarController.modalPresentationStyle = .custom
                self.present(mainTabBarController, animated: true, completion: nil)
            }
        case 1:
            print("error")
        case 2:
            print("error2")
        case 3:
            print("error3")
        case 4:
            print("error4")
        case 5:
            print("error5")
        default:
            break
        }
    }
}

The problem is that even if the emailFieldSignIn.text! and passwordFieldSignIn.text! are empty it still segues you to the mainTabBarController without any validation of the data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The POST request from APICallerPOST class :

func signInToAccount(username: String, password: String, completion: @escaping (SignInResponse?, Error?) -> Void) {
    
    //declare parameter as a dictionary which contains string as key and value combination.
    let parameters = ["User": username, "Password": password]
    
    //create the url with NSURL
    let url = URL(string: "https://censoredurl/Signin")!
    
    //create the session object
    let session = URLSession.shared
    
    //now create the Request object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST
    
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
    } catch let error {
        print(error.localizedDescription)
        completion(nil, error)
    }
    
    //HTTP Headers
    request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
    
    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in
        
        guard error == nil else {
            completion(nil, error)
            return
        }
        
        guard let data = data else {
            completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
            return
        }
        
        do {
            //create json object from data
            let decoder = JSONDecoder()
                    
            guard let json = try? decoder.decode(SignInResponse.self, from: data) else {
               completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
               return
            }
            
            print(json)
            completion(json, nil)
            
        } catch let error {
            print(error.localizedDescription)
            completion(nil, error)
        }
    })
    
    task.resume()
}

>Solution :

Please check my answer it will be helpfull for you I have added compulsory checks to validate if UITextfields are empty or not you can also add valid email check.

  @IBAction func signInSegueToDashboard(_ sender: Any) {
                if emailFieldSignIn.text!.isEmpty || passwordFieldSignIn.text!.isEmpty{
    //                show some error
                     return
                 }
                APICallerPOST.shared.signInToAccount(username: emailFieldSignIn.text!, password: passwordFieldSignIn.text!) { [self] (result, error) in
                    
                    switch result?.StatusCode {
                    case 0:
                        DispatchQueue.main.async {
                            
                            activityLoaderSignIn.startAnimating()
                        }
                        
                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                            
                            guard let mainTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "mainTabBarController")
                            else {
                                return
                            }
                            
                            self.activityLoaderSignIn.stopAnimating()
                            mainTabBarController.modalPresentationStyle = .custom
                            self.present(mainTabBarController, animated: true, completion: nil)
                        }
                    case 1:
                        print("error")
                    case 2:
                        print("error2")
                    case 3:
                        print("error3")
                    case 4:
                        print("error4")
                    case 5:
                        print("error5")
                    default:
                        break
                    }
                }
            }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading