Important: This check should always be performed asynchronously. The majority of answers below are synchronous so be careful otherwise you'll freeze up your app.
Swift
1) Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift
2) Test reachability via closures
let reachability = Reachability()!
reachability.whenReachable = { reachability in
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
reachability.whenUnreachable = { _ in
print("Not reachable")
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
Objective-C
1) Add SystemConfiguration
framework to the project but don't worry about including it anywhere
2) Add Tony Million's version of Reachability.h
and Reachability.m
to the project (found here: https://github.com/tonymillion/Reachability)
3) Update the interface section
#import "Reachability.h"
@interface MyViewController ()
{
Reachability *internetReachableFoo;
}
@end
4) Then implement this method in the .m file of your view controller which you can call
- (void)testInternetConnection
{
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
internetReachableFoo.reachableBlock = ^(Reachability*reach)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Yayyy, we have the interwebs!");
});
};
internetReachableFoo.unreachableBlock = ^(Reachability*reach)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Someone broke the internet :(");
});
};
[internetReachableFoo startNotifier];
}
Important Note: The Reachability
class is one of the most used classes in projects so you might run into naming conflicts with other projects. If this happens, you'll have to rename one of the pairs of Reachability.h
and Reachability.m
files to something else to resolve the issue.
Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.
return (BOOL)URLString;
, or even better,return !!URLString
orreturn URLString != nil
– user529758NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://twitter.com/getibox"] encoding:NSUTF8StringEncoding error:nil];
To get rid of the annoying warning. – Abdelrahman Eid