Monday, 18 June 2012

Check Wifi & Internet Connectivity in an iPhone APP

I faced a problem in my Application that i would like t discuss here :
If wifi is ON but there is no or low internet connectivity, how to resolve it.


Below is the sample code :




+(void)ApplicationStatus
{
    bool success = false;
    const char *host_name = [@"www.google.com" cStringUsingEncoding:NSASCIIStringEncoding];


    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName (NULL, host_name);
    SCNetworkReachabilityFlags flags;
    success = SCNetworkReachabilityGetFlags(reachability, &flags);
    bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);


    if (isAvailable)
    {
        NSLog(@"Host is reachable: %d", flags);
        // Perform Action if Wifi is reachable and Internet Connectivity is present
    }
    else
    {
        NSLog(@"Host is unreachable");
        // Perform Action if Wifi is reachable and Internet Connectivity is not present
    }      
}


When  ApplicationStatus method is called we check that "www.google.com" is reachable or not.
SCNetworkReachabilityFlags returns flags which helps us to understand the Status of internet connectivity.
If isAvailable variable returns "true" then Host is Reachable means Wifi is reachable and Internet Connectivity is present else there is NO Internet Connectivity.

No comments:

Post a Comment