Search code examples
iosobjective-ciphonereachability

Internet reachability not working properly in iPhone


I am working on an application which continously tracking internet connectivity and upload some data, app have the feature that when internet is not available it saves data(photos) offline and on internet availability it uploads the data. My app working fine but sometimes its not chechking internet and when i turned off my device wifi and again turn on, It is working, So can anybody please tell me whats wrong here that stuck me? my reachability code is as below:

code

- (void)reachabilityCheck
{
    /* Internet checking  */
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

    Reachability *reach = [Reachability reachabilityForInternetConnection];
    reach.reachableOnWWAN = YES;
    [reach startNotifier];
    NetworkStatus internetStatus = [reach currentReachabilityStatus];
    if (internetStatus != NotReachable) {
        //Develop By Payal
        if(self.internetConnection == 0)
        {
            NSLog(@"Connection active");
            self.internetConnection = 1;
        }
        //Develop By Payal Done
    }
    else {
        NSLog(@"Connection inactive");
        self.internetConnection = 0;
    }
}

Solution

  • Try this code

    Put bellow code in your viewDidLoad method it call the instantly using notification

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(checkNetworkStatus:)
                                                     name:kReachabilityChangedNotification object:nil];
    
    
    
    //Net Connection Chack
    - (void)checkNetworkStatus:(NSNotification *)notice
    {
        // called after network status changes
    
        NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
        switch (internetStatus)
        {
            case NotReachable:
            {
                NSLog(@"The internet is down.");
                UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"Error" message:@"No Internet Connection\nPlease Check The Connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alrt show];
    
                break;
            }
            case ReachableViaWiFi:
            {
                NSLog(@"The internet is working via WIFI");
                break;
            }
            case ReachableViaWWAN:
            {
                NSLog(@"The internet is working via WWAN!");
                break;
            }
        }
    }
    

    i hope this usefull you