Created
August 31, 2016 08:55
-
-
Save sanghapark/52fbfb1a14945f9b30f1eefc0ce3ad84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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