Checking Http Status Swift4

2020-07-30 02:28发布

问题:

I'm a bit confused about credentials and HttpStatus.

I'm making a login page in Swift 4/XCode9, that connects to an api. Here is what I do when the login button is tapped:

   @IBAction func loginTapped(_ sender: Any) {

    let loginString = String(format: "%@:%@", usernametext.text!, passwordtext.text!)
    let loginData = loginString.data(using: String.Encoding.utf8)!
    let base64LoginString = loginData.base64EncodedString()
    var Base = base64LoginString

    let url = URL(string: "SOME URL")!
    var request = URLRequest(url: url)
    request.addValue("Basic \(Base)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("\(error)")
            return
        }
        if let httpStatus = response as? HTTPURLResponse {
            print("status code = \(httpStatus.statusCode)")
        }
    }
    task.resume()
    view.endEditing(true)
}

Everything works fine but I don't know how to check the httpstatus. If I get wrong credentials I want to stay on the login page and not perform segue to the next view.

回答1:

Try this code

func checkStatusCode(response:URLResponse?) -> Bool {
        guard let statusCode = (response as? HTTPURLResponse)?.statusCode else {
            print("Invalid Response")
            return false
        }

        if statusCode != 200 {
            print("Invalid File")            
            return false
        }
        return true
    }

Usage:

if (self.checkStatusCode(response: response)) { 
    DispatchQueue.main.async {
        self.performSegue(withIdentifier: "showW", sender: self)
    }      
} else {
 //added an alert 
}