Created
March 6, 2023 08:48
-
-
Save tornikegomareli/b769ec3f505c5a66af7a8a26419d29f0 to your computer and use it in GitHub Desktop.
NetworkConnectionProvider
This file contains 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
// | |
// 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