Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import UIKit
  2. import Alamofire
  3.  
  4. enum ReachabilityManagerError: Error {
  5. case notReachable
  6. }
  7.  
  8. struct ReachabilityManager {
  9.  
  10. /// singleton
  11. static let `default` : ReachabilityManager = {
  12. let manager = ReachabilityManager()
  13. // configuration
  14. return manager
  15. }()
  16.  
  17. /// Alamofire (NetworkReachabilityManager)
  18. let networkManager = NetworkReachabilityManager()!
  19.  
  20. /// key to send notification by changing the status of the network
  21. let listenerNetworkStatusChanged = NSNotification.Name(rawValue:"NSNotificationKeyListenerNetworkStatusChanged")
  22.  
  23. //MARK:-
  24. //MARK: check network
  25.  
  26. /// check internet connection
  27. ///
  28. /// - returns: network status
  29. func checkInternetConnection() -> Bool {
  30. switch networkManager.networkReachabilityStatus {
  31. case NetworkReachabilityManager.NetworkReachabilityStatus.notReachable, NetworkReachabilityManager.NetworkReachabilityStatus.unknown:
  32. return false
  33. default:
  34. return true
  35. }
  36. }
  37.  
  38. /// check internet connection (throws)
  39. ///
  40. /// - throws: in the absence of network
  41. func checkConnection() throws {
  42. switch networkManager.networkReachabilityStatus {
  43. case NetworkReachabilityManager.NetworkReachabilityStatus.notReachable,
  44. NetworkReachabilityManager.NetworkReachabilityStatus.unknown:
  45. throw ReachabilityManagerError.notReachable
  46. default: return
  47. }
  48. }
  49.  
  50. //MARK:-
  51. //MARK: listening
  52.  
  53. /// start
  54. ///
  55. func startNetworkListening() {
  56. networkManager.listener = { status in
  57.  
  58. /// - unknown: It is unknown whether the network is reachable.
  59. /// - notReachable: The network is not reachable.
  60. /// - reachable: The network is reachable.
  61.  
  62. NotificationCenter.default.post(name: self.listenerNetworkStatusChanged,
  63. object: nil,
  64. userInfo: ["NetworkStatus": status])
  65. }
  66.  
  67. networkManager.startListening()
  68. }
  69.  
  70. /// stop
  71. ///
  72. func stopNetworkListening() {
  73. networkManager.stopListening()
  74. }
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement