How to test connection in swift

3

I have a very simple webview, and before loading the webview I want to check the connection, if it is unavailable, create a message for the user informing.

    
asked by anonymous 06.01.2015 / 19:04

1 answer

2

The best solution is you do not test but rather wait for the error to make a decision.

Testing if the user has a connection does not mean that after the test, his decision will be correct, because the connection may change status during the execution of the decision made, so you may fall into the same problem. >

Example with a pseudo code:

testConnection({ hasConnection in
  if hasConnection {
    getContentOnline()
  }
  else {
    getContentOffline()
  }
})
  • The callback will not execute immediately, you will have to wait, that is, it may take a while.
  • It is not 100% since the connection may stop responding during the request and then you will fall into the same problem.
  • As you said, you do not need to test, you need to implement a fallback if the app fails to load the data and in this case you need to implement the - webView:didFailLoadWithError: method of UIWebViewDelegate .

    Below are the reasons for failure or lack of data connection of the device, that you can handle them easily using a switch :

    // assumindo que você receba um erro do callback webView:didFailLoadWithError
    switch ([error code]){
      case NSURLErrorInternationalRoamingOff:
      case NSURLErrorCallIsActive:
      case NSURLErrorDataNotAllowed:
      case NSURLErrorNotConnectedToInternet:
      // Testar falha de rede com Reachabiity
      break;
    
      default:
      break;
    }
    

    If you received one of these codes, you can use Reachability to:

  • To test whether the host is "reachable", if so, you can try again or ask the user to try again (with a reload button for example).
  • To show that the user is offline.
  • To warn the user that his network is in trouble.
  • I use this approach a lot for practically everything networking, this keeps your app always responsive, fast and does not burden data and user time with testing.

    Hope it helps, good coding.

        
    23.03.2015 / 15:43