How To Check Response.statusCode in sendSynchronousRequest on Swift
How To check response.statusCode in SendSynchronousRequest in Swift The Code is Below :
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?
before and in objective c , we check response.statusCode With this : (long)response.statusCode but in swift i have no idea how can check response status Code
you pass in a reference to response so it is filled THEN you check the result and cast it to a HTTPResponse as only http responses declare the status code property.
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)")
}
note: in objC you would also use the same approach but if you use squared brackets, the compiler doesn't enforce the cast. Swift (being type safe) does enforce the cast always
Swift 3 version for @GarySabo answer:
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()
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()
I use an extension to URLResponse to simplify this one (Swift 3):
extension URLResponse {
func getStatusCode() -> Int? {
if let httpResponse = self as? HTTPURLResponse {
return httpResponse.statusCode
}
return nil
}
}