Skip to content

Instantly share code, notes, and snippets.

@rwbutler
Last active Jan 26, 2022
Embed
What would you like to do?
OpenConnectivity Usage Example
import OpenCombine
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
private var cancellable: AnyCancellable?
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// ...
let connectivity: ConnectivityService = OpenConnectivityService()
cancellable = connectivity.publisher
.sink { result in
print(result)
}
return true
}
}
import Foundation
struct ConnectivityResult {
enum ConnectionStatus {
case connected
case connectedWithoutInternet
case determining
case disconnected
}
enum ConnectionType {
case cellular
case ethernet
case unknown
case wifi
}
let connectionStatus: ConnectionStatus
let connectionType: ConnectionType?
}
extension ConnectivityResult: CustomStringConvertible {
var description: String {
return "\(connectionStatus) via \(String(describing: connectionType))"
}
}
import Foundation
import OpenCombine
protocol ConnectivityService {
var publisher: AnyPublisher<ConnectivityResult, Never> { get }
}
import Connectivity
import Foundation
import OpenCombine
import OpenConnectivity
class OpenConnectivityService: ConnectivityService {
private var cancellable: AnyCancellable?
private let internalPublisher = ConnectivityPublisher()
var publisher: AnyPublisher<ConnectivityResult, Never> {
internalPublisher
.map { connectivity in
let connectionStatus: ConnectivityResult.ConnectionStatus
let connectionType: ConnectivityResult.ConnectionType?
switch connectivity.status {
case .connected:
connectionStatus = .connected
connectionType = .unknown
case .connectedViaCellular:
connectionStatus = .connected
connectionType = .cellular
case .connectedViaCellularWithoutInternet:
connectionStatus = .connectedWithoutInternet
connectionType = .cellular
case .connectedViaEthernet:
connectionStatus = .connected
connectionType = .ethernet
case .connectedViaEthernetWithoutInternet:
connectionStatus = .connectedWithoutInternet
connectionType = .ethernet
case .connectedViaWiFi:
connectionStatus = .connected
connectionType = .wifi
case .connectedViaWiFiWithoutInternet:
connectionStatus = .connectedWithoutInternet
connectionType = .wifi
case .determining:
connectionStatus = .determining
connectionType = nil
case .notConnected:
connectionStatus = .disconnected
connectionType = nil
}
return ConnectivityResult(connectionStatus: connectionStatus, connectionType: connectionType)
}.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment