ViewController.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. let useClosures = false
  10. class ViewController: UIViewController {
  11. @IBOutlet weak var networkStatus: UILabel!
  12. let reachability = Reachability.reachabilityForInternetConnection()
  13. override func viewDidLoad() {
  14. super.viewDidLoad()
  15. if (useClosures) {
  16. reachability?.whenReachable = { reachability in
  17. self.updateLabelColourWhenReachable(reachability)
  18. }
  19. reachability?.whenUnreachable = { reachability in
  20. self.updateLabelColourWhenNotReachable(reachability)
  21. }
  22. } else {
  23. NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
  24. }
  25. reachability?.startNotifier()
  26. // Initial reachability check
  27. if let reachability = reachability {
  28. if reachability.isReachable() {
  29. updateLabelColourWhenReachable(reachability)
  30. } else {
  31. updateLabelColourWhenNotReachable(reachability)
  32. }
  33. }
  34. }
  35. deinit {
  36. reachability?.stopNotifier()
  37. if (!useClosures) {
  38. NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
  39. }
  40. }
  41. func updateLabelColourWhenReachable(reachability: Reachability) {
  42. if reachability.isReachableViaWiFi() {
  43. self.networkStatus.textColor = UIColor.greenColor()
  44. } else {
  45. self.networkStatus.textColor = UIColor.blueColor()
  46. }
  47. self.networkStatus.text = reachability.currentReachabilityString
  48. }
  49. func updateLabelColourWhenNotReachable(reachability: Reachability) {
  50. self.networkStatus.textColor = UIColor.redColor()
  51. self.networkStatus.text = reachability.currentReachabilityString
  52. }
  53. func reachabilityChanged(note: NSNotification) {
  54. let reachability = note.object as! Reachability
  55. if reachability.isReachable() {
  56. updateLabelColourWhenReachable(reachability)
  57. } else {
  58. updateLabelColourWhenNotReachable(reachability)
  59. }
  60. }
  61. }