divendres, 21 de febrer del 2014

Checking network availability


In order to check the network availability of your device you can use the Apple Reachability class.  You can even hook up to be notified of network status changes through the ReachabilityCallback. 

But if you prefer a  a quick and dirty solution use this:
Write the following C code and save on a file named Goodies.h:


#include<unistd.h>
#include<netdb.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>


extern bool is_NetworkAvailable();

The matching implementation is Goodies.m


#include <stdio.h>
#include "Goodies.h"


bool is_NetworkAvailable()
{
    char *hostname;
    hostname = "google.com";
    
    struct addrinfo *res = NULL;
    int s = getaddrinfo(hostname, "http", NULL, &res);
    bool network_ok = (s == 0 && res != NULL);
    freeaddrinfo(res);
    if (network_ok ) {
        return 1;
    }
    else {
        return 0;
    }
    

}

And that's all. Now import Goodies.h an you can use the function is_NetworkAvailable() everywhre.
 



boolean _isNetworkAvailable = is_NetworkAvailable();

if (_isNetworkAvailable) {

          // Network related tasks

} else {

       UIAlertView *message = [[UIAlertView alloc]                                initWithTitle:@"Alert"
                 message:@"Nointernet connectivity." delegate:nil
                 cancelButtonTitle:@"OK"
                 otherButtonTitles:nil];

      [message show];

}

Cap comentari:

Publica un comentari a l'entrada