fred
fred

Reputation: 157

How to use Reachability in xcode for assessment Internet Connection

Im new in iphone and I want know that how to use Reachability in xcode. I go on to Reachability example and read about it but understand about it. I create one application and put Reachability.m and Reachability.h in it but I dont know how to use from it.

please guide me. I want when run application check my network Connection any time and run this code :

if (isConnection)
{
NSLog(@"Connection Success")
}
else
NSLog(@"Connection has been lost")

Upvotes: 1

Views: 5718

Answers (2)

Bajaj
Bajaj

Reputation: 869

Download Reachability Classes and Follow this code

internetReach = [[Reachability reachabilityForInternetConnection] retain];
[internetReach startNotifier];

Then we’ll set the NetworkStatus variable created in Reachability.

NetworkStatus netStatus = [internetReach currentReachabilityStatus];

And finally we’ll use the netStatus in a switch block.

switch (netStatus)
{            
    case ReachableViaWWAN:
    {
        break;
    }
    case ReachableViaWiFi:
    {
        break;
    }
    case NotReachable:
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"We are unable to make a internet connection at this time. Some functionality will be limited until a connection is made." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];   
        [alert release];
        break;
    }

}

- (void) reachabilityChanged: (NSNotification* )note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);

    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus)
    {
        case ReachableViaWWAN:
        {
            break;
        }
        case ReachableViaWiFi:
        {
            break;
        }
        case NotReachable:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"We are unable to make a internet connection at this time. Some functionality will be limited until a connection is made." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];   
            [alert release];
            break;
        }
    }
}

Upvotes: 0

Rui Peres
Rui Peres

Reputation: 25917

You can do this:

 Reachability *reachability = [Reachability reachabilityForInternetConnection];
 NetworkStatus internetStatus = [reachability currentReachabilityStatus];

And now check the internetStatus var, by inspecting its value. The values are defined as:

typedef enum 
{
    // Apple NetworkStatus Compatible Names.
    NotReachable     = 0,
    ReachableViaWiFi = 2,
    ReachableViaWWAN = 1
} NetworkStatus;

So, in your case:

if (internetStatus == NotReachable)
{
   NSLog(@"Bazinga!");
}
else
{
   NSLog(@"Houston we have ignition");
}

Upvotes: 2

Related Questions