ViewController.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // ViewController.swift
  3. // Reachability Sample
  4. //
  5. // Created by Ashley Mills on 22/09/2014.
  6. // Copyright (c) 2014 Joylord Systems. All rights reserved.
  7. //
  8. import UIKit
  9. import Reachability
  10. let useClosures = false
  11. class ViewController: UIViewController {
  12. @IBOutlet weak var networkStatus: UILabel!
  13. var reachability: Reachability?
  14. override func viewDidLoad() {
  15. super.viewDidLoad()
  16. do {
  17. let reachability = try Reachability.reachabilityForInternetConnection()
  18. self.reachability = reachability
  19. } catch ReachabilityError.FailedToCreateWithAddress(let address) {
  20. networkStatus.textColor = UIColor.redColor()
  21. networkStatus.text = "Unable to create\nReachability with address:\n\(address)"
  22. return
  23. } catch {}
  24. if (useClosures) {
  25. reachability?.whenReachable = { reachability in
  26. self.updateLabelColourWhenReachable(reachability)
  27. }
  28. reachability?.whenUnreachable = { reachability in
  29. self.updateLabelColourWhenNotReachable(reachability)
  30. }
  31. } else {
  32. NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
  33. }
  34. do {
  35. try reachability?.startNotifier()
  36. } catch {
  37. networkStatus.textColor = UIColor.redColor()
  38. networkStatus.text = "Unable to start\nnotifier"
  39. return
  40. }
  41. // Initial reachability check
  42. if let reachability = reachability {
  43. if reachability.isReachable() {
  44. updateLabelColourWhenReachable(reachability)
  45. } else {
  46. updateLabelColourWhenNotReachable(reachability)
  47. }
  48. }
  49. }
  50. deinit {
  51. reachability?.stopNotifier()
  52. if (!useClosures) {
  53. NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
  54. }
  55. }
  56. func updateLabelColourWhenReachable(reachability: Reachability) {
  57. if reachability.isReachableViaWiFi() {
  58. self.networkStatus.textColor = UIColor.greenColor()
  59. } else {
  60. self.networkStatus.textColor = UIColor.blueColor()
  61. }
  62. self.networkStatus.text = reachability.currentReachabilityString
  63. }
  64. func updateLabelColourWhenNotReachable(reachability: Reachability) {
  65. self.networkStatus.textColor = UIColor.redColor()
  66. self.networkStatus.text = reachability.currentReachabilityString
  67. }
  68. func reachabilityChanged(note: NSNotification) {
  69. let reachability = note.object as! Reachability
  70. if reachability.isReachable() {
  71. updateLabelColourWhenReachable(reachability)
  72. } else {
  73. updateLabelColourWhenNotReachable(reachability)
  74. }
  75. }
  76. }