Thursday, 24 May 2018

How to check an active internet connection on iPhone/iOS

Background

There are various network calls that we may have to make from your device to server. Internet network connection may not always be available for review. So it is better if we can check if the network is reachable before making the API calls. In this post, we will see the same in Objective C.


How to check an active internet connection on iPhone/iOS

  • First, add SystemConfiguration framework to your project.
  • To do this double click on your project. This should open your project settings. Select your app target.



  • Now go to "Build Phases" Tab on the top
  • Now Expand "Link Binary With Libraries"
  • Now click on '+' icon and search for "SystemConfiguration"
  • You should see "SystemConfiguration.framework"
  • Select it and click Add
  • You should see it would be added under "Link Binary With Libraries"


  • You should also start seeing "Framework" group under project navigator -

  • Now add Tony Million's version of Reachability.h and Reachability.m to the project. You can find it here - https://github.com/tonymillion/Reachability
  • I have just created a new group called Reachability and added these file in it.


  • In the file where you want to make this change import Reachability 
    • #import "Reachability.h"
  • Now you can check if the internet is available with following code snippet -


    if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
    {
        //connection unavailable
        NSLog(@"Connection is not available");
    }
    else
    {
        //connection available
         NSLog(@"Connection is available");
    }



NOTE#import <SystemConfiguration/SystemConfiguration.h> is inside Reachability.h. You do not have to explicitly import it anywhere. Just add it to the framework.




Related Links


No comments:

Post a comment

t> UA-39527780-1 back to top