Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift
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") }
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") }
Add
SystemConfigurationframework to the project but don't worry about including it anywhereAdd Tony Million's version of
Reachability.handReachability.mto the project (found here: https://github.com/tonymillion/Reachability)Update the interface section
#import "Reachability.h"
// Add this to the interface in the .m file of your view controller @interface MyViewController () { Reachability *internetReachableFoo; } @end
#import "Reachability.h" // Add this to the interface in the .m file of your view controller @interface MyViewController () { Reachability *internetReachableFoo; } @endThen implement this method in the .m file of your view controller which you can call
// Checks if we have an internet connection or not
(void)testInternetConnection {
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];// Internet is reachable internetReachableFoo.reachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Yayyy, we have the interwebs!"); }); };
// Internet is not reachable internetReachableFoo.unreachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Someone broke the internet :("); }); };
[internetReachableFoo startNotifier]; }
// Checks if we have an internet connection or not - (void)testInternetConnection { internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"]; // Internet is reachable internetReachableFoo.reachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Yayyy, we have the interwebs!"); }); }; // Internet is not reachable internetReachableFoo.unreachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Someone broke the internet :("); }); }; [internetReachableFoo startNotifier]; }