Sydney Loteria
Sydney Loteria

Reputation: 10451

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 ?

Upvotes: 0

Views: 3614

Answers (5)

JSBach
JSBach

Reputation: 446

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();
    }

}

Upvotes: 0

Luis
Luis

Reputation: 1150

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()

Upvotes: 4

Hasya
Hasya

Reputation: 9898

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.")

    }
}

Upvotes: 0

Mahendra
Mahendra

Reputation: 8904

- (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];
}

Upvotes: 0

Ketan Parmar
Ketan Parmar

Reputation: 27428

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 :)

Upvotes: 1

Related Questions