Skip to content

Instantly share code, notes, and snippets.

@dimohamdy
Last active May 17, 2022 01:31
Show Gist options
  • Save dimohamdy/5166ba6c88f6954fa6b23bc9f28cbe12 to your computer and use it in GitHub Desktop.
Save dimohamdy/5166ba6c88f6954fa6b23bc9f28cbe12 to your computer and use it in GitHub Desktop.
Check internet Reachability iOS 12+
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Reachability.shared.startNetworkReachabilityObserver()
return true
}
}
import Foundation
protocol NotificationName {
var name: Notification.Name { get }
}
extension RawRepresentable where RawValue == String, Self: NotificationName {
var name: Notification.Name {
return Notification.Name(rawValue)
}
}
enum Notifications {
enum Reachability: String, NotificationName {
case connected
case notConnected
}
}
// Check internet connection
if Reachability.shared.isConnected {
print("no internet connection")
}
// Observe internet connection
[Notifications.Reachability.connected.name,
Notifications.Reachability.notConnected.name].forEach { (notification) in
NotificationCenter.default.addObserver(self, selector: #selector(changeInternetConnection), name: notification, object: nil)
}
@objc
private func changeInternetConnection(notification: Notification) {
if notification.name == Notifications.Reachability.notConnected.name {
showError(title: Strings.noInternetConnectionTitle.localized())
}
}
import Network
import Foundation
class Reachability {
static var shared = Reachability()
lazy private var monitor = NWPathMonitor()
var isConnected: Bool {
return monitor.currentPath.status == .satisfied
}
func startNetworkReachabilityObserver() {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
NotificationCenter.default.post(name: Notifications.Reachability.connected.name, object: nil)
} else if path.status == .unsatisfied {
NotificationCenter.default.post(name: Notifications.Reachability.notConnected.name, object: nil)
}
}
let queue = DispatchQueue.global(qos: .background)
monitor.start(queue: queue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment