How to use NetworkReachabilityManager in Alamofire - ios
I want functionality similar to AFNetworking in Objective-C with Alamofire NetworkReachabilityManager in Swift:
//Reachability detection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN: {
[self LoadNoInternetView:NO];
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi: {
[self LoadNoInternetView:NO];
break;
}
case AFNetworkReachabilityStatusNotReachable: {
break;
}
default: {
break;
}
}
}];
I am currently using the listener to know the status changes with network
let net = NetworkReachabilityManager()
net?.startListening()
Can someone describe how to support those use cases?
NetworkManager Class
class NetworkManager {
//shared instance
static let shared = NetworkManager()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")
func startNetworkReachabilityObserver() {
reachabilityManager?.listener = { status in
switch status {
case .notReachable:
print("The network is not reachable")
case .unknown :
print("It is unknown whether the network is reachable")
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
case .reachable(.wwan):
print("The network is reachable over the WWAN connection")
}
}
// start listening
reachabilityManager?.startListening()
}
}
Start Network Reachability Observer
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// add network reachability observer on app start
NetworkManager.shared.startNetworkReachabilityObserver()
return true
}
}
I found the answer myself i.e by just writing a listener with closure as mentioned below:
let net = NetworkReachabilityManager()
net?.listener = { status in
if net?.isReachable ?? false {
switch status {
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
case .reachable(.wwan):
print("The network is reachable over the WWAN connection")
case .notReachable:
print("The network is not reachable")
case .unknown :
print("It is unknown whether the network is reachable")
}
}
net?.startListening()
Here's my implementation. I use it in a singleton. Remember to hold on to the reachability manager reference.
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
func listenForReachability() {
self.reachabilityManager?.listener = { status in
print("Network Status Changed: \(status)")
switch status {
case .NotReachable:
//Show error state
case .Reachable(_), .Unknown:
//Hide error state
}
}
self.reachabilityManager?.startListening()
}
SWIFT 5
NetworkState Structure
import Foundation
import Alamofire
struct NetworkState {
var isInternetAvailable:Bool
{
return NetworkReachabilityManager()!.isReachable
}
}
Use: -
if (NetworkState().isInternetAvailable) {
// Your code here
}
Using a singleton is working as I long as you keep a reference of reachabilityManager
class NetworkStatus {
static let sharedInstance = NetworkStatus()
private init() {}
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
func startNetworkReachabilityObserver() {
reachabilityManager?.listener = { status in
switch status {
case .notReachable:
print("The network is not reachable")
case .unknown :
print("It is unknown whether the network is reachable")
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
case .reachable(.wwan):
print("The network is reachable over the WWAN connection")
}
}
reachabilityManager?.startListening()
}
So you can use it like this anywhere in your app:
let networkStatus = NetworkStatus.sharedInstance
override func awakeFromNib() {
super.awakeFromNib()
networkStatus.startNetworkReachabilityObserver()
}
You will be notified of any change in your network status.
Just for icing on the cake this is a very good animation to show on your internet connection loss.
Swift 5:
No need for listener object . Just we need to call the closure :
struct Network {
let manager = Alamofire.NetworkReachabilityManager()
func state() {
manager?.startListening { status in
switch status {
case .notReachable :
print("not reachable")
case .reachable(.cellular) :
print("cellular")
case .reachable(.ethernetOrWiFi) :
print("ethernetOrWiFi")
default :
print("unknown")
}
}
}
}
You can start using this function like :
Network().state()
Apple says to use a struct instead of a class when you can. So here's my version of #rmooney and #Ammad 's answers, but using a struct instead of a class. Additionally, instead of using a method or function, I am using a computed property and I got that idea from this Medium post by #Abhimuralidharan. I'm just putting both the idea of using a struct instead of a class (so you don't have to have a singleton) and using a computed property instead of a method call together in one solution.
Here's the struct NetworkState:
import Foundation
import Alamofire
struct NetworkState {
var isConnected: Bool {
// isReachable checks for wwan, ethernet, and wifi, if
// you only want 1 or 2 of these, the change the .isReachable
// at the end to one of the other options.
return NetworkReachabilityManager(host: www.apple.com)!.isReachable
}
}
Here is how you use it in any of your code:
if NetworkState().isConnected {
// do your is Connected stuff here
}
To create NetworkManager Class as follows (For SWIFT 5)
import UIKit
import Alamofire
class NetworkManager {
static let shared = NetworkManager()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
func startNetworkReachabilityObserver() {
reachabilityManager?.startListening(onUpdatePerforming: { status in
switch status {
case .notReachable:
print("The network is not reachable")
case .unknown :
print("It is unknown whether the network is reachable")
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
case .reachable(.cellular):
print("The network is reachable over the cellular connection")
}
})
}
}
And the usage will be like
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// add network reachability observer on app start
NetworkManager.shared.startNetworkReachabilityObserver()
return true
}
}
Alamofire 5 and above
import Alamofire
// MARK: NetworkReachability
final class NetworkReachability {
static let shared = NetworkReachability()
private let reachability = NetworkReachabilityManager(host: "www.apple.com")!
typealias NetworkReachabilityStatus = NetworkReachabilityManager.NetworkReachabilityStatus
private init() {}
/// Start observing reachability changes
func startListening() {
reachability.startListening { [weak self] status in
switch status {
case .notReachable:
self?.updateReachabilityStatus(.notReachable)
case .reachable(let connection):
self?.updateReachabilityStatus(.reachable(connection))
case .unknown:
break
}
}
}
/// Stop observing reachability changes
func stopListening() {
reachability.stopListening()
}
/// Updated ReachabilityStatus status based on connectivity status
///
/// - Parameter status: `NetworkReachabilityStatus` enum containing reachability status
private func updateReachabilityStatus(_ status: NetworkReachabilityStatus) {
switch status {
case .notReachable:
print("Internet not available")
case .reachable(.ethernetOrWiFi), .reachable(.cellular):
print("Internet available")
case .unknown:
break
}
}
/// returns current reachability status
var isReachable: Bool {
return reachability.isReachable
}
/// returns if connected via cellular
var isConnectedViaCellular: Bool {
return reachability.isReachableOnCellular
}
/// returns if connected via cellular
var isConnectedViaWiFi: Bool {
return reachability.isReachableOnEthernetOrWiFi
}
deinit {
stopListening()
}
}
How to use:
Call NetworkReachability.shared.startListening() from AppDelegate to start listening for reachability changes
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NetworkReachability.shared.startListening()
// window and rootviewcontroller setup code
return true
}
}
Solution for swift 4* + swift 5* and Alamofire 4.5+
CREATE a NetworkReachabilityManager class from Alamofire and
configure the checkNetwork() method
import Alamofire
class Connectivity {
class func checkNetwork() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
USAGE
switch Connectivity.checkNetwork() {
case true:
print("network available")
//perform task
case false:
print("no network")
}
Just slight Improvement in the Alamofire 5
class NetworkManager {
//shared instance
static let shared = NetworkManager()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")
func startNetworkReachabilityObserver() {
reachabilityManager?.startListening { status in
switch status {
case .notReachable:
print("The network is not reachable")
case .unknown :
print("It is unknown whether the network is reachable")
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
case .reachable(.cellular):
print("The network is reachable over the cellular connection")
}
}
}
}
Related
DNSProxyProvider is not getting installed
I've created a MacOS app project which contains System Network Extension (DNS proxy). With help of https://developer.apple.com/forums/thread/81103?answerId=246229022 and How to use NEDNSProxyProvider in iOS 11. I enabled DNSProxyProvider. When I built the app for the first time a prompt asked to allow the system extension. I allowed it and Under network in system preference, I can see DNS is not running (yellow dot). Not running I added OSSystemextensionRequest from the container App. This is my code. import Cocoa import NetworkExtension import SystemExtensions import OSLog class ViewController: NSViewController { let log=OSLog(subsystem:"com.example.applesamplecode.DNSTestBed", category: "app") let manager = NEDNSProxyManager.shared() private func installSystemExtension() { os_log("DNSFProxy: installing system extension") let request = OSSystemExtensionRequest.activationRequest( forExtensionWithIdentifier: "my system extension's bundle indentifier", queue: .main ) request.delegate = self OSSystemExtensionManager.shared.submitRequest(request) } private func enable() { NSLog("enabled already ",self.manager.isEnabled ) NSLog(self.manager.isEnabled ? "Yes" : "No") self.update { self.manager.localizedDescription = "DNS" let proto = NEDNSProxyProviderProtocol() proto.serverAddress = "localhost" proto.providerBundleIdentifier = "my system extension's bundle indentifier" self.manager.providerProtocol = proto self.manager.isEnabled = true } NSLog(self.manager.isEnabled ? "Yes" : "No") } private func disable() { self.update { self.manager.isEnabled = false } } private func update(_ body: #escaping () -> Void) { self.manager.loadFromPreferences { (error) in guard error == nil else { NSLog("DNS Test App: load error") return } body() self.manager.saveToPreferences { (error) in guard error == nil else { NSLog("DNS Test App: save error") return } NSLog("DNS Test App: saved") } } } override func viewDidLoad() { super.viewDidLoad() self.enable() self.installSystemExtension() } } extension ViewController: OSSystemExtensionRequestDelegate { func request(_ request: OSSystemExtensionRequest, actionForReplacingExtension existing: OSSystemExtensionProperties, withExtension ext: OSSystemExtensionProperties) -> OSSystemExtensionRequest.ReplacementAction { os_log("DNSProxy: Replacing extension %# version %# with version %#", request.identifier, existing.bundleShortVersion, ext.bundleShortVersion) return .replace } func requestNeedsUserApproval(_ request: OSSystemExtensionRequest) { os_log("DNSProxy: Extension %# requires user approval", request.identifier) } func request(_ request: OSSystemExtensionRequest, didFailWithError error: Error) { os_log("DNSProxy: System extension request failed: %#", error.localizedDescription) } /* Other delegate methods here */ func request(_ request: OSSystemExtensionRequest, didFinishWithResult result: OSSystemExtensionRequest.Result) { switch result { case .completed: var manager = NEDNSProxyManager.shared() case .willCompleteAfterReboot: os_log("DNSProxy: willCompleteAfterReboot") #unknown default: os_log("DNSProxy: default") } } } Info.plist of system extension: info.plist I'm getting an error when the activation request happens: The operation couldn’t be completed. (OSSystemExtensionErrorDomain error 1.). Any help would be great. Thanks. P.S: I also posted this in apple forums https://developer.apple.com/forums/thread/717647
update the Viewcontroller based on Network Availblilty in swift
I am new to ios development, i have to check the internet network based on that i will show the view controllers, i used this code for test the network. class Connectivity { class func isConnectedToInternet() ->Bool { return NetworkReachabilityManager()!.isReachable } } if Connectivity.isConnectedToInternet() { print("Yes! internet is available.") // do some tasks.. } else { } with this code i am getting network network status, my aim is when the application launch time if don't have network show the default page, if enable the network automatically it will show the main page please help me.
try this code let reachability = Reachability()! NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability) do{ try reachability.startNotifier() }catch{ print("could not start reachability notifier") } #objc func reachabilityChanged(note: Notification) { let reachability = note.object as! Reachability switch reachability.connection { case .wifi: print("Reachable via WiFi") case .cellular: print("Reachable via Cellular") case .none: print("Network not reachable") } }
Alamofire - NetworkReachabilityManager doesn't work with .notReachable
I have an issue with NetworkReachabilityManager from Alamofire. I tried to test the connection with this example code: override func viewDidLoad() { super.viewDidLoad() let manager = NetworkReachabilityManager(host: "www.apple.com") manager?.listener = { status in switch status { case .notReachable: print("network connection status - lost") case .reachable(NetworkReachabilityManager.ConnectionType.ethernetOrWiFi): print("network connection status - ethernet/WiFI") case .reachable(NetworkReachabilityManager.ConnectionType.wwan): print("network connection status - wwan") default: break } } manager?.startListening() } When I tried to turn the wifi off and I received only blank response. No response like such as "network connection status - lost". But when I tried to turn on the wifi and I received the result "network connection status - ethernet/WiFI" in which is good response. Any idea what is wrong with .notReachable? Any suggestion appreciated.
According to Alamofire "Make sure to remember to retain the manager" so create a manager like this class A: UIViewController{ let manager = NetworkReachabilityManager(host: "www.apple.com") override func viewDidLoad() { super.viewDidLoad() // before start listening you can check if (manager?.isReachableOnEthernetOrWiFi == true) { print("internet is available") } else { print("internet is not available") } manager?.startListening() manager?.listener = { status in switch status { case .notReachable: print("network connection status - lost") case .reachable(NetworkReachabilityManager.ConnectionType.ethernetOrWiFi): print("network connection status - ethernet/WiFI") case .reachable(NetworkReachabilityManager.ConnectionType.wwan): print("network connection status - wwan") default: break } } } }
How do I use this code in a singleton in swift?
I have this code that I found here. Now I would like to know how to use it in a singleton. My understanding is if I use this code in a singleton I will be noticed if there is a change in the network status. func startNetworkReachabilityObserver() { let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com") reachabilityManager?.listener = { status in switch status { case .NotReachable: print("The network is not reachable") case .Unknown : print("It is unknown whether the network is reachable") case .Reachable(.EthernetOrWiFi): print("The network is reachable over the WiFi connection") case .Reachable(.WWAN): print("The network is reachable over the WWAN connection") } } // start listening reachabilityManager?.startListening() }
Using a singleton is working as I long as you keep a reference of reachabilityManager class NetworkStatus { static let sharedInstance = NetworkStatus() private init() {} let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com") func startNetworkReachabilityObserver() { reachabilityManager?.listener = { status in switch status { case .notReachable: print("The network is not reachable") case .unknown : print("It is unknown whether the network is reachable") case .reachable(.ethernetOrWiFi): print("The network is reachable over the WiFi connection") case .reachable(.wwan): print("The network is reachable over the WWAN connection") } } reachabilityManager?.startListening() } } So you can use it like this: let networkStatus = NetworkStatus.sharedInstance override func awakeFromNib() { super.awakeFromNib() networkStatus.startNetworkReachabilityObserver() } You will be notified of any change in your network status.
Hoist the variable into the class as a property. Add a static shared property to make your class a singleton. class ReachabilityManager { private let networkReachabilityManager = NetworkReachabilityManager() static let shared = ReachabilityManager() private override init () { super.init() networkReachabilityManager?.listener = { status in //Post Notifications here } } } func startListening() { networkReachabilityManager.startListening() } } The static properties are lazy by default so when you call ReachabilityManager.shared.startListening() it will instantiate the singleton the first time and subsequent calls use the existing shared instance.
AFNetworking Reachability Manager in Swift
Is there a way in Swift that the AFNetworking Reachability will continuously checking the internet connection every second, so far this is what I have and it only check one time only: override func viewDidLoad() { AFNetworkReachabilityManager.sharedManager().startMonitoring() AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock{(status: AFNetworkReachabilityStatus?) in switch status!.hashValue { case AFNetworkReachabilityStatus.NotReachable.hashValue: print("no internet") case AFNetworkReachabilityStatus.ReachableViaWiFi.hashValue,AFNetworkReachabilityStatus.ReachableViaWWAN.hashValue: print("with internet") default: print("unknown") } } } How to check internet connection continuously ?
AFNetworking Reachability does check continuously the connection, I'm using it if a few of my apps and it does the job well. If your code is not working, I believe it might be because you call startMonitoring before setting the handler with setReachabilityStatusChangeBlock, so you might miss an initial event. Also, unrelated to your problem but an improvement you can make, you don't need to use the hashValue in the switch statement, you can use statusdirectly, and you get the benefit of the Swift compiler checking for the completion of the case statements. In summary, give a try to the following version of your code and see if it works: AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status: AFNetworkReachabilityStatus) -> Void in switch status { case .NotReachable: print("Not reachable") case .ReachableViaWiFi, .ReachableViaWWAN: print("Reachable") case .Unknown: print("Unknown") } } AFNetworkReachabilityManager.sharedManager().startMonitoring()
You should not check for rechability for every minute or periodically. It's not good practice, it's decrease the performance of app. You can get rechability change notifications. so when rechabilty change you can perform some task You can do something like this, You must create a Reachability object before you can receive notifications from it. Also, be sure to call the startNotifier() method on the Reachability object you create. This would be an example of how to do so inside of your application delegate: class AppDelegate: UIResponder, UIApplicationDelegate { private var reachability:Reachability!; func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: kReachabilityChangedNotification, object: nil); self.reachability = Reachability.reachabilityForInternetConnection(); self.reachability.startNotifier(); } func checkForReachability(notification:NSNotification) { // Remove the next two lines of code. You cannot instantiate the object // you want to receive notifications from inside of the notification // handler that is meant for the notifications it emits. //var networkReachability = Reachability.reachabilityForInternetConnection() //networkReachability.startNotifier() let networkReachability = notification.object as Reachability; var remoteHostStatus = networkReachability.currentReachabilityStatus() if (remoteHostStatus.value == NotReachable.value) { println("Not Reachable") } else if (remoteHostStatus.value == ReachableViaWiFi.value) { println("Reachable via Wifi") } else { println("Reachable") } } } You can download reachability class from Apple Documentation Hope this will help :)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // internetReachable is declared as property. internetReachable = [Reachability reachabilityForInternetConnection]; [internetReachable startNotifier]; [[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; } - (void)checkNetworkStatus:(NSNotification *)notice { // called when network status is changed NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; switch (internetStatus) { case NotReachable: { NSLog(#"The internet is down."); break; } case ReachableViaWiFi: { NSLog(#"The internet is Connected."); break; } case ReachableViaWWAN: { NSLog(#"The internet is working via WWAN!"); break; } } //#import "Reachability.m" static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) { #pragma unused (target, flags) NSCAssert(info != NULL, #"info was NULL in ReachabilityCallback"); NSCAssert([(__bridge NSObject*) info isKindOfClass: [Reachability class]], #"info was wrong class in ReachabilityCallback"); Reachability* noteObject = (__bridge Reachability *)info; // Post a notification to notify the client that the network reachability changed. [[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject]; }
You can utilize - https://github.com/ashleymills/Reachability.swift //declare this inside of viewWillAppear do { reachability = try Reachability.reachabilityForInternetConnection() } catch { print("Unable to create Reachability") return } NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:",name: ReachabilityChangedNotification,object: reachability) do{ try reachability?.startNotifier() }catch{ print("could not start reachability notifier") } //declare this inside of viewWillDisappear reachability!.stopNotifier() NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: reachability) func reachabilityChanged(note: NSNotification) { let reachability = note.object as! Reachability if reachability.isReachable() { print("NETWORK REACHABLE.") } if reachability.isReachableViaWiFi() { print("NETWORK REACHABLE VIA WIFI.") } if reachability.isReachableViaWWAN() { print("NETWORK REACHABLE VIA WWAN.") } else { print("NETWORK NOT REACHABLE.") } }
Also for my own archiving purposes. You can use this one as #Lion in his/her answer suggests. Just call Reachability.registerListener() inside didFinishLaunchingWithOptions in AppDelegate.swift. It will automatically inform you on changes. // // CheckInternet.swift // // Created by Dincer on 14/11/15. // import AFNetworking public class Reachability { private static let theSharedInstance:Reachability = Reachability(); private var isClientOnline:Bool = true; private var isClientWiFi:Bool = false; private var isClientConnectionUnknown = false; func onOnline() { print("****************************************** Network goes online."); } func onOffline() { print("****************************************** Network goes offline."); } func onWiFi() { print("****************************************** Wifi network on"); } func onGSM() { print("****************************************** GSM network on"); } func onUnknownConnectionStatus() { print("****************************************** Unkown network status"); } func isConnectedToNetwork() -> Bool { return isClientOnline; } func isConnectedToWiFi() -> Bool { return isClientOnline && isClientWiFi; } static func sharedInstance() -> Reachability { return Reachability.theSharedInstance; } static func registerListener() { sharedInstance().registerListener(); } func registerListener() { AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status: AFNetworkReachabilityStatus) -> Void in switch status { case .NotReachable: self.isClientConnectionUnknown = false; if self.isClientOnline { self.isClientOnline = false; self.onOffline(); } case .ReachableViaWiFi: self.isClientConnectionUnknown = false; if !self.isClientOnline { self.isClientOnline = true; self.onOnline(); } if !self.isClientWiFi { self.isClientWiFi = true; self.onWiFi(); } case .ReachableViaWWAN: self.isClientConnectionUnknown = false; if !self.isClientOnline { self.isClientOnline = true; self.onOnline(); } if self.isClientWiFi { self.isClientWiFi = false; self.onGSM(); } case .Unknown: if !self.isClientConnectionUnknown { self.isClientConnectionUnknown = true; self.onUnknownConnectionStatus(); } } } AFNetworkReachabilityManager.sharedManager().startMonitoring(); } }