how to check the connection to the Internet

how to check the connection to the Internet?

Check out Apple's Reachability sample code. There are some third party extensions based on that as well. I've been using one called "JTSReachability" that can be found on GitHub.


(Disclaimer: I have not yet checked to see if it works with IPv6. That will be a requirement soon.)

Look into creating an NSURLConnection or NSURLSession. If you get back a nil then it couldn't find the Internet.

I checked my code. Here is what I do. I establish an NSURLSession and then start a task. If the device is not connected to the internet then the localizedDiscription of the error will be "The Internet connection appears to be offline." If the device is connected to the internet then this is the code to handle it - so I don't do a pre-test for internet connection. Here is the code:


//   in the.h file you need to add:
    @interface theClassName : NSObject<NSURLSessionTaskDelegate,NSURLSessionDataDelegate>


//   then somewhere in .m establish the session and start a task looking for a website stored in webSiteString....
    NSURLSession *theConnection=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    [[theConnection dataTaskWithURL:[NSURL URLWithString:webSiteString]] resume];

// and here is the method for handling the response if it is an error
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    dispatch_async(dispatch_get_main_queue(), ^{
      if(error){
        UIAlertView *anError;
        anError = [[UIAlertView alloc]
                   initWithTitle:@"Web Error"
                   message: [error localizedDescription]
                   delegate: nil
                   cancelButtonTitle:@"OK"
                   otherButtonTitles:nil ] ;
        [anError show];
        return;
      }else{
         //  the data was received in URLSession:dataTask:didReceiveData:
         //  the task has now ended, handle the response based on the received data
      }
    });
}
how to check the connection to the Internet
 
 
Q