How to test Swift connection

Asked

Viewed 693 times

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.

  • One of the great advantages of Swift is the possibility to use codes in Objective-C, that is, you can still use the Reachability together. Otherwise, this guy also did something similar with own Swift from this very library.

  • the use if Reachability.isConnectedToNetwork() { networkStatusLabel.text = "Internet Connection: Available" networkStatusLabel.textColor = Uicolor.greenColor() } Else { networkStatusLabel.text = "Internet Connection: Unavailable" networkStatusLabel.textColor = Uicolor.redColor() } this already resolves?

1 answer

2

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

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

Example with pseudo code:

testConnection({ hasConnection in
  if hasConnection {
    getContentOnline()
  }
  else {
    getContentOffline()
  }
})
  1. The callback will not run immediately, you will need to wait, IE, may take.
  2. It is not 100% since the connection may stop responding during the request and then you will fall into the same problem.

As I said, you don’t need to test, what you need is to implement a fallback if the app can’t load the data and in this case, you need to implement the method - webView:didFailLoadWithError: of UIWebViewDelegate.

Below are the reasons for failure or lack of device data connection, which 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:

  1. To test if the host is "Reachable", if yes, you can try again or ask the user to try again (with a reload button for example).
  2. To show that the user is offline.
  3. To let the user know his network is in trouble.

I use this approach a lot for virtually everything networking, this keeps your app always responsive, fast and does not burden data and user time with testing.

I hope it helps, good coding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.