As you wished in the comments above here is a solution using a "HEAD" request.
- Make your class conforming to the NSURLConnectionDelegate.
- Implement the
connection:didReceiveResponse:
delegate method - Optionally implement the
connection:didFailWithError:
delegate method
So your setup could look like this:
YourClass.m
@interface YourClass () <NSURLConnectionDelegate>
@property (strong, nonatomic) NSURLConnection *headerConnection;
@end
@implementation YourClass
- (void)viewDidLoad {
// You can do this in whatever method you want
NSMutableURLRequest *headerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
headerRequest.HTTPMethod = @"HEAD";
self.headerConnection = [[NSURLConnection alloc] initWithRequest:headerRequest delegate:self];
}
#pragma mark - NSURLConnectionDelegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (connection == self.headerConnection) {
// Handle the case that you have Internet; if you receive a response you are definitely connected to the Internet
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Note: Check the error using `error.localizedDescription` for getting the reason of failing
NSLog(@"Failed: %@", error.localizedDescription);
}