|
|
@@ -9,19 +9,34 @@
|
|
|
import UIKit
|
|
|
import Reachability
|
|
|
|
|
|
-let useClosures = false
|
|
|
-
|
|
|
class ViewController: UIViewController {
|
|
|
|
|
|
@IBOutlet weak var networkStatus: UILabel!
|
|
|
+ @IBOutlet weak var hostNameLabel: UILabel!
|
|
|
|
|
|
var reachability: Reachability?
|
|
|
|
|
|
override func viewDidLoad() {
|
|
|
super.viewDidLoad()
|
|
|
|
|
|
+ // Start reachability without a hostname intially
|
|
|
+ setupReachability(useHostName: false, useClosures: true)
|
|
|
+ startNotifier()
|
|
|
+
|
|
|
+ // After 5 seconds, stop and re-start reachability, this time using a hostname
|
|
|
+ let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(5) * NSEC_PER_SEC))
|
|
|
+ dispatch_after(dispatchTime, dispatch_get_main_queue()) {
|
|
|
+ self.stopNotifier()
|
|
|
+ self.setupReachability(useHostName: true, useClosures: true)
|
|
|
+ self.startNotifier()
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ func setupReachability(useHostName useHostName: Bool, useClosures: Bool) {
|
|
|
+ let hostName = "google.com"
|
|
|
+ hostNameLabel.text = useHostName ? hostName : "No host name"
|
|
|
do {
|
|
|
- let reachability = try Reachability.reachabilityForInternetConnection()
|
|
|
+ let reachability = try useHostName ? Reachability(hostname: hostName) : Reachability.reachabilityForInternetConnection()
|
|
|
self.reachability = reachability
|
|
|
} catch ReachabilityError.FailedToCreateWithAddress(let address) {
|
|
|
networkStatus.textColor = UIColor.redColor()
|
|
|
@@ -39,7 +54,9 @@ class ViewController: UIViewController {
|
|
|
} else {
|
|
|
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
|
|
|
}
|
|
|
-
|
|
|
+ }
|
|
|
+
|
|
|
+ func startNotifier() {
|
|
|
do {
|
|
|
try reachability?.startNotifier()
|
|
|
} catch {
|
|
|
@@ -49,13 +66,10 @@ class ViewController: UIViewController {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- deinit {
|
|
|
-
|
|
|
+ func stopNotifier() {
|
|
|
reachability?.stopNotifier()
|
|
|
-
|
|
|
- if (!useClosures) {
|
|
|
- NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
|
|
|
- }
|
|
|
+ NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
|
|
|
+ reachability = nil
|
|
|
}
|
|
|
|
|
|
func updateLabelColourWhenReachable(reachability: Reachability) {
|
|
|
@@ -87,6 +101,11 @@ class ViewController: UIViewController {
|
|
|
updateLabelColourWhenNotReachable(reachability)
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ deinit {
|
|
|
+ stopNotifier()
|
|
|
+ }
|
|
|
+
|
|
|
}
|
|
|
|
|
|
|