ubaltaci
ubaltaci

Reputation: 1016

Reachability Class with IP

I modified apple's reachability class to use with my server ip. But when I use reachabilityWithAddress it's not called reachabilityChanged while app is launching. It is called only internet connection status changed. ( like turning wi-fi off, on ) But, if I use reachabilityWithHostName, reachabilityChanged function called when app is launching.

What am I missing?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    ///////////////////////////////////////////////////////////////////////////////////
    // Reachability Local Notifications 
    ///////////////////////////////////////////////////////////////////////////////////
    hasInternetConnection = NO;
    struct sockaddr_in address;
    address.sin_len = sizeof(address);
    address.sin_family = AF_INET;
    address.sin_port = htons(80);
    address.sin_addr.s_addr = inet_addr("X.X.X.X");
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name:kReachabilityChangedNotification object: nil];
    hostReach = [Reachability reachabilityWithAddress:&address];
    [hostReach startNotifier];

    ...

}

Then in method:

-(void)reachabilityChanged:(NSNotification*)note
   {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    if ( curReach == hostReach ) {
        NetworkStatus netStatus = [curReach currentReachabilityStatus]; 
        if ( netStatus != ReachableViaWiFi && netStatus != ReachableViaWWAN ) {
            hasInternetConnection = NO;
        }
        else {
            hasInternetConnection = YES;
        }
    }
    else {
        DLog(@"Something go wrong!");
    }
}

Upvotes: 2

Views: 1970

Answers (1)

George
George

Reputation: 1990

When using the reachabilityWithHostName: selector you get a notification soon after initializing Reachability b/c the reachability of the host name is not known until that name is resolved. For reachabilityWithAddress:, the reachability status is already known so there's no change to report.

I got around the problem by adding the following three lines to the inner most "if" block in the reachabilityWithAddress: function.

SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(reachability, &flags);
ReachabilityCallback(reachability, flags, retVal);

This calls the same callback function that would be called if reachability had actually changed. So if you're completely depending on the notification, like I am, this will cause the notification to post after initializing reachability.

Upvotes: 2

Related Questions