Skip to content

Instantly share code, notes, and snippets.

@sanghapark
Created August 31, 2016 08:55
Show Gist options
  • Save sanghapark/52fbfb1a14945f9b30f1eefc0ce3ad84 to your computer and use it in GitHub Desktop.
Save sanghapark/52fbfb1a14945f9b30f1eefc0ce3ad84 to your computer and use it in GitHub Desktop.
import Foundation
import Alamofire
enum NetworkStatus {
case WWAN
case EthernetOrWiFi
case NotReachable
case Unknown
}
protocol NetworkReachabilityDelegate : class {
func didChanageNetworkStatus(status: NetworkStatus)
}
class NetworkReachability {
private typealias Listener = NetworkReachabilityManager.NetworkReachabilityStatus -> Void
static let shared = NetworkReachability()
private let rechability = NetworkReachabilityManager()
private var status: NetworkStatus = .Unknown
var delegates = [NetworkReachabilityDelegate?]()
func networkStatus() -> NetworkStatus {
return status
}
func startListening() {
rechability?.listener = { status in
switch status {
case .Unknown :
self.status = .Unknown
case .NotReachable :
self.status = .NotReachable
case .Reachable(let connectionType) :
if connectionType == .EthernetOrWiFi {
self.status = .EthernetOrWiFi
} else if connectionType == .WWAN {
self.status = .WWAN
}
}
LogUtils.printDebug(status)
self.delegates.forEach { $0?.didChanageNetworkStatus(self.status) }
}
rechability?.startListening()
}
func subscribe(observer: NetworkReachabilityDelegate) {
let results = delegates.filter { $0 === observer }
if results.count < 1 {
delegates.append(observer)
}
}
func unscribe(observer: NetworkReachabilityDelegate) {
let indexes = delegates.enumerate().filter { $0.element === observer }.map { $0.index }
indexes.forEach { delegates.removeAtIndex($0) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment