Reputation: 725
I request a web page with this code
URLSession.shared.dataTask(with: NSURL(string: url)! as URL, completionHandler: { (data, response, error) -> Void in
if error == nil && data != nil {
// No error
}else{
// Error
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode)
}
}
I am trying to get the error code when requesting a page by casting the response to HTTPURLResponse
but the cast dose not work and the print is not executed. Do you know how can I get the code?
Upvotes: 4
Views: 4911
Reputation: 9077
I needed a solution to this and here is the code I got to through a lot of testing:
func getChuckNorrisDat() async -> String{
var data: Data? = nil
var response: HTTPURLResponse? = nil
do {
(data, response) = try await (URLSession.shared.data(from: URL(string:"https://api.chucknorris.io/jokes/random-")!) as? (Data, HTTPURLResponse))!
// catches errors in response from web api -- so web api has been
// successfully contacted but a "normal" status error occurs
// Other bad errors throw exceptions which is caught below
// bad URL like string:"https://api.chucknorris.io/jokes/random-"
// real URL is https://api.chucknorris.io/jokes/random (no dash at end)
// will cause this error (404)
switch response?.statusCode{
case _ where response!.statusCode < 200 || response!.statusCode >= 300:
return "Couldn't carry on. Bad status code from API \(response?.statusCode)"
default:
print("Success!")
}
}
catch{
// catches errors when the URL is not well formed
// bad URL like the following causes this exception:
// (notice the x in the protocol portion of URL
// string:"httpxs://api.chucknorris.io/jokes/random"
print("!! What ERROR? \(error.localizedDescription)")
return "\(error.localizedDescription)"
}
return "failed!"
}
First thing I do is set up the two variables data
and response
to hold the returned values from the call to the data()
method.
Notice that we have to cast the response
to a HTTPURLResponse
so we will have the .statusCode
property available.
The rest is explained in the code sample.
This works great.
Upvotes: -1
Reputation: 1607
Your if let httpResponse
code runs only in the else
branch of the error checking if
statement. You might also want to check the response in such cases when no error has occurred.
Upvotes: 1