Skip to content

Instantly share code, notes, and snippets.

@tornikegomareli
Created March 6, 2023 08:48
Show Gist options
  • Save tornikegomareli/b769ec3f505c5a66af7a8a26419d29f0 to your computer and use it in GitHub Desktop.
Save tornikegomareli/b769ec3f505c5a66af7a8a26419d29f0 to your computer and use it in GitHub Desktop.
NetworkConnectionProvider
//
// NetworkConnetionProvider.swift
//
//
// Created by Tornike on 12.12.22.
//
import Foundation
import Reachability
public protocol ConnectionListener: AnyObject {
func networkConnectionDidChanged(status: Reachability.Connection)
}
public class NetworkConnetionProvider {
let multicastDelegate = MulticastDelegate<ConnectionListener>()
var reachability: Reachability?
init() {
do {
// TODO: Need to replace it with environmental URL's
reachability = try Reachability()
try reachability?.startNotifier()
startMonitoring()
} catch {
reachability = nil
print("NetworkManager: Can't create instance of Reachability")
}
}
private func reachabilityChanged(with status: Reachability.Connection) {
multicastDelegate.invokeDelegates { listener in
DispatchQueue.main.async {
listener.networkConnectionDidChanged(status: status)
}
}
}
public func startMonitoring() {
reachability?.whenReachable = { [weak self] reachability in
guard let weakSelf = self else {
return
}
weakSelf.reachabilityChanged(with: reachability.connection)
}
reachability?.whenUnreachable = { [weak self] reachability in
guard let weakSelf = self else {
return
}
weakSelf.reachabilityChanged(with: reachability.connection)
}
}
public func stopMonitoring() {
reachability?.stopNotifier()
}
public func addListener(listener: ConnectionListener) {
multicastDelegate.addDelegate(listener)
}
public func removeListener(listener: ConnectionListener) {
multicastDelegate.removeDelegate(listener)
}
public func isReachable(
success: @escaping (() -> Void) = {},
failure: @escaping (() -> Void) = {}) {
DispatchQueue.main.async {
(self.reachability?.connection != .unavailable) ? success() : failure()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment