user1898829
user1898829

Reputation: 3527

How can I display message to user as soon as internet disappears using reachability with afnetworking 2.0

I have this in side of my AppDelegate's application didFinishLaunchingWithOptions. The code gets called to show alert controller but nothing happens.

AFNetworkReachabilityManager.sharedManager().startMonitoring()
    AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock{(status: AFNetworkReachabilityStatus?)          in
        switch status!.hashValue{
        case AFNetworkReachabilityStatus.NotReachable.hashValue:
            println("Not reachable")
            let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Button", style: UIAlertActionStyle.Default, handler: nil))
            AppDelegate.sharedInstance.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
        case AFNetworkReachabilityStatus.ReachableViaWiFi.hashValue , AFNetworkReachabilityStatus.ReachableViaWWAN.hashValue :
            println("Reachable")
            println(AppDelegate.sharedInstance.description)
        default:
            println("Unknown status")
        }
    }

I also have this class in my AppDelegate.

class var sharedInstance: AppDelegate {
    struct Static {
        static let instance = AppDelegate()
    }
    return Static.instance
}

Upvotes: 0

Views: 186

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

Didn't notice the AppDelegate.sharedInstance bit at first. That's not how you get access to your app delegate - you need the one that is created by the UIApplication that's running your whole app. Your code should be:

AFNetworkReachabilityManager.sharedManager().startMonitoring()
AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock{
    (status: AFNetworkReachabilityStatus?) in

    switch status!.hashValue {
    case AFNetworkReachabilityStatus.NotReachable.hashValue:
        println("Not reachable")
        let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Button", style: UIAlertActionStyle.Default, handler: nil))
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        appDelegate.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)

    case AFNetworkReachabilityStatus.ReachableViaWiFi.hashValue, AFNetworkReachabilityStatus.ReachableViaWWAN.hashValue :
        println("Reachable")
        println(AppDelegate.sharedInstance.description)

    default:
        println("Unknown status")
    }
}

Upvotes: 1

Related Questions