Cómo Comprobar La Respuesta.Código de estado en sendSynchronousRequest en Swift


Cómo comprobar la respuesta.Código de estado en sendSynchronousRequest en Swift El Código es el Siguiente :

let urlPath: String = "URL_IS_HERE"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil

var error: NSErrorPointer? = nil
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: nil) as NSData?

Antes y en el objetivo c , comprobamos la respuesta.Código de estado Con esto : respuesta.Código de estado pero en swift no tengo idea de cómo puede comprobar el código de estado de respuesta

Author: pacification, 2014-10-04

6 answers

Pasa una referencia a response para que se rellene, luego comprueba el resultado y lo envía a un HttpResponse, ya que solo las respuestas http declaran la propiedad status code.

let urlPath: String = "http://www.google.de"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var response: NSURLResponse?

var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

if let httpResponse = response as? NSHTTPURLResponse {
    println("error \(httpResponse.statusCode)")
}

nota: en ObjC también usarías el mismo enfoque, pero si usas corchetes, el compilador no hace cumplir el cast. Swift (siendo tipo seguro) hace cumplir el cast siempre

 60
Author: Daij-Djan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-14 10:03:02

Versión Swift 3 para @GarySabo respuesta:

let url = URL(string: "https://apple.com")!
let request = URLRequest(url: url)

let task = URLSession.shared().dataTask(with: request) {data, response, error in

    if let httpResponse = response as? HTTPURLResponse {
        print("statusCode: \(httpResponse.statusCode)")
    }

}
task.resume()
 49
Author: DazChong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-14 10:03:32

Limpiado para Swift 2.0 usando NSURLSession

let urlPath: String = "http://www.google.de"
let url: NSURL = NSURL(string: urlPath)!
let request: NSURLRequest = NSURLRequest(URL: url)
var response: NSURLResponse?


let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {urlData, response, reponseError in

         if let httpResponse = response as? NSHTTPURLResponse {
             print("error \(httpResponse.statusCode)")  
          }

 }
 task.resume()
 //You should not write any code after `task.resume()`
 6
Author: GarySabo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-01 04:57:21

Utilizo una extensión para URLResponse para simplificar esta (Swift 3):

extension URLResponse {

    func getStatusCode() -> Int? {
        if let httpResponse = self as? HTTPURLResponse {
            return httpResponse.statusCode
        }
        return nil
    }
}
 6
Author: eskimwier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-10 23:01:44

Swift 3+

let dataURL = "https://myurl.com"
        var request = URLRequest(url: URL(string: dataURL)!)
        request.addValue("Bearer \(myToken)", forHTTPHeaderField: "Authorization")
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            // Check if the response has an error
            if error != nil{
                print("Error \(String(describing: error))")
                return
            }

            if let httpResponse = response as? HTTPURLResponse{
                if httpResponse.statusCode == 401{
                    print("Refresh token...")
                    return
                }
            }

            // Get data success

        }.resume()
 5
Author: Dasoga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-26 13:55:17

Si utilizas la biblioteca Just sería tan simple como:

Just.get("URL_IS_HERE").statusCode
 2
Author: Daniel Duan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-06 00:51:25