1

I'm using swiftHTTP for requesting to my server and when my internet connection is slow, it goes to response part! I've set the example code below:

HTTP.GET("myURL") { response in
  let myResponse = response.data // it comes here after the timeout
  if response.statusCode == 200 {
    //some code
  } else {
       do {
         let jsonError = try JSON(data: myResponse) // in this line it goes to catch because there is no data in myresponse
       } catch{
         //alert for not having connection
       }
}

Why does it call the response function if there's no response?
My server also says, that no request was sent.

thatmarcel
  • 388
  • 3
  • 15
Azin Nilchi
  • 849
  • 1
  • 10
  • 24

2 Answers2

1

It doesn't "go to response", it tries to make the HTTP request as expected and regardless of success or error it's completion handler is called.

The response object that is returned is an object that contains all of the information you need to determine what happened with the request.

So it will contain a timeout status code (HTTP 408), possibly an error message. If it did not respond at all, your app would not be able to handle these cases.

Say for example your user taps on their profile icon in the app and this sends a request to get the users profile, but it timed out. Do you want the user sat waiting, looking at a blank profile screen? It's much better to catch the error and handle it gracefully. In this case you could present a message to the user telling them that something went wrong and close the empty profile screen

Scriptable
  • 19,402
  • 5
  • 56
  • 72
1

Your response handler will also be called from swiftHTTP, if there's no or a very bad connection.
To solve this problem, either check if there is an internet connection or check if the data is nil:

HTTP.GET("myURL") { response in
  let myResponse = response.data // it comes here after the timeout
  if response.statusCode == 200 || response.data == nil {
    //some code
  } else {
       do {
         let jsonError = try JSON(data: myResponse) // in this line it goes to catch because there is no data in myresponse
       } catch{
         //alert for not having connection
       }
}

The important part here is the check if response.data == nil.

thatmarcel
  • 388
  • 3
  • 15