Search code examples
iosconnectionios9uialertaction

Check Internet Connection fails in iOS 9?


after iOS 9, I used to check if my app had connection with my server with the next part of code, and If there is no response, I asked user to activate wifi, etc.

Alert which show the dialog:

    #pragma mark - SHOW ALERTVIEW FOR IOS 7 or less AND IOS 8
-(void) alertNoInternet:(NSString*)alertTitle withMessage:(NSString *)alertMessage{

    NSString *alert3gButtonText = @"Mobile Data";
    NSString *alertWifiButtonText = @"WIFI";
    NSString *alertCancelButtonText = @"Cancel";


    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( NSFoundationVersionNumber_iOS_8_0 ) ) {
        NSLog(@"SQA: iOS 8 dialog process");
        /*id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
         if([rootViewController isKindOfClass:[UINavigationController class]])
         {
         rootViewController = [((UINavigationController *)rootViewController).viewControllers objectAtIndex:0];
         }*/

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
                                                                                 message:alertMessage
                                                                          preferredStyle:UIAlertControllerStyleActionSheet];
        //We add buttons to the alert controller by creating UIAlertActions:
        UIAlertAction *action3g = [UIAlertAction actionWithTitle:alert3gButtonText
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action)
                                   {
                                       NSURL *urlCellular = [NSURL URLWithString:@"prefs:root=General&path=USAGE/CELLULAR_USAGE"];

                                       if([[UIApplication sharedApplication] canOpenURL:urlCellular]) {
                                           [[UIApplication sharedApplication] openURL:urlCellular];
                                       }


                                       [alertController dismissViewControllerAnimated:YES completion:nil];
                                       //home button press programmatically
                                       UIApplication *app = [UIApplication sharedApplication];
                                       [app performSelector:@selector(suspend)];

                                       //wait 2 seconds while app is going background
                                       [NSThread sleepForTimeInterval:2.0];

                                       //exit app when app is in background
                                       exit(0);
                                   }];

        //We add buttons to the alert controller by creating UIAlertActions:
        UIAlertAction *actionWifi = [UIAlertAction actionWithTitle:alertWifiButtonText
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action)
                                     {
                                         NSURL *urlWifi = [NSURL URLWithString:@"prefs:root=WIFI"];

                                         if ([[UIApplication sharedApplication] canOpenURL:urlWifi]) {
                                             [[UIApplication sharedApplication] openURL:urlWifi];
                                         }

                                         [alertController dismissViewControllerAnimated:YES completion:nil];
                                         //home button press programmatically
                                         UIApplication *app = [UIApplication sharedApplication];
                                         [app performSelector:@selector(suspend)];

                                         //wait 2 seconds while app is going background
                                         [NSThread sleepForTimeInterval:2.0];

                                         //exit app when app is in background
                                         exit(0);
                                     }];


        //We add buttons to the alert controller by creating UIAlertActions:
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:alertCancelButtonText
                                                               style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action)
                                       {
                                           [alertController dismissViewControllerAnimated:YES completion:nil];
                                           //home button press programmatically
                                           UIApplication *app = [UIApplication sharedApplication];
                                           [app performSelector:@selector(suspend)];

                                           //wait 2 seconds while app is going background
                                           [NSThread sleepForTimeInterval:2.0];

                                           //exit app when app is in background
                                           exit(0);
                                       }];


        //[alertController addAction:action3g];
        [alertController addAction:actionWifi];
        [alertController addAction:actionCancel];
        [self presentViewController:alertController animated:YES completion:nil];
    }

    if (SYSTEM_VERSION_LESS_THAN(NSFoundationVersionNumber_iOS_7_0) ) {
        NSLog(@"SQA: iOS 7 or less dialog process");

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                            message:alertMessage
                                                           delegate:nil
                                                  cancelButtonTitle:alertCancelButtonText
                                                  otherButtonTitles:alertWifiButtonText, nil];
        alertView.tag = TAG_ALERT_NOINTERNET;
        [alertView show];
    }
}

And this is the source code to check the connection:

- (void)checkInternet:(connection)block
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURL *url = [NSURL URLWithString:@"http://www.tempdevserver.com/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"HEAD";
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
    request.timeoutInterval = 10.0;

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:
     ^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
         block([(NSHTTPURLResponse *)response statusCode] == 200);
     }];
}

Now, on iOS 9, dialog is always shown, and never let me pass from there. What has changed?


Solution

  • Here is the perfect solution, might be helpful to you.

    **in your Appdelegate.m File**
    
    //Check Internet Plugin
    #include<unistd.h>
    #include<netdb.h>
    /////
    
    #pragma mark Check Internet connection
    -(BOOL)checkInternetConnection {
    
        char *hostname;
        struct hostent *hostinfo;
        hostname = "google.com";
        hostinfo = gethostbyname (hostname);
        if (hostinfo == NULL)
        {
            NSLog(@"-> no connection!\n");
            return NO;
        }
        else{
            NSLog(@"-> connection established!\n");
            return YES;
        }
    }
    

    Try above code, it is working fine and perfect.