Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 455
hossein1448 Avatar asked Oct 04 '14 09:10

hossein1448


People also ask

How to get the status code of the response object?

Noticed, getStatusCode () method can be used to get the status code of the Response. This method returns an integer and test will verify the value of this integer.

What is the status code for HTTP request?

If the Request is successful, Status Code 200 is returned. status code. If the Request is not successful, Status Code other than 200 will be returned. Get a list of HTTP Status codes and there meanings on the W3 page.

How to test if a status code is returned correctly?

Once the status code is received, it is compared with the expected value of 200. // Assert that correct status code is returned. Assert.assertEquals (statusCode /*actual value*/, 200 /*expected value*/, "Correct status code returned"); Try running the test and notice that the test will pass.

How to produce a successful HTTP response status code 200?

Below is a code example which should produce a successful HTTP Response Status code 200. Provided that the URL path parameter of userId (tov5c2VC2c1RKXeM80rCtgXVmGN6Kj) is correct. If your Web Service Endpoint does not require Authorization Header, then simply do not set the Header value in your code.


1 Answers

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

like image 157
Daij-Djan Avatar answered Sep 22 '22 03:09

Daij-Djan