Reachability.swift: Simpler usage?

Created on 8 Jan 2016  路  9Comments  路  Source: ashleymills/Reachability.swift

The examples in the documentation seem quite code-heavy, and focuses on reachability state changes. In a reachability library I used before (IJReachability, which is no longer updated), I was able to to do this:

if IJReachability.isConnectedToNetwork() {
    print("connected")
} else {
    print("not connected")
}

... for a one-off check on reachability. Is something similar possible with Reachability.swift ?

Documentation

Most helpful comment

Hey Guys, I made it work in my Swift project with the code below in my AppDelegate.swift file for reachabilityswift.

import ReachabilitySwift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

var reach: Reachability?

var window: UIWindow?        

    // Reachability code
    // Allocate a reachability object
    do {
    self.reach = try Reachability.reachabilityForInternetConnection()
    } catch {
      // Handle it 馃憤          
    }
    // Set the blocks
    self.reach!.whenReachable = {
        (let reach: Reachability!) -> Void in
        // keep in mind this is called on a background thread
        // and if you are updating the UI it needs to happen
        // on the main thread, like this:
        dispatch_async(dispatch_get_main_queue()) {
            print("REACHABLE!")
        }
    }

    self.reach!.whenUnreachable = {
        (let reach: Reachability!) -> Void in
        print("UNREACHABLE!")
    }
    do {
           try self.reach!.startNotifier()
    } catch {
      // Handle it 馃憤    
    }

    return true
}

All 9 comments

Hi,

You can absolutely do that:

let reachability = try! Reachability.reachabilityForInternetConnection()

if reachability.currentReachabilityStatus == .NotReachable {
    print("not connected")
} else {
    print("connected")
}

Hope that helps
Ash

in the Example - notifications code section it give the error on the below line

reachability.startNotifier()
Error is : Call can throw, but it is not marked with 'try' and the error is not handled

i fixed this error by doing like that
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}

But its didn't work for me please somebody help quickly

would suggest above code example from @ashleymills be added to the Readme

Good call - I'll get on it.

Cheers
Ash

Wouldn't be something like

let reachability = try? Reachability.reachabilityForInternetConnection()
if reachability == nil || reachability!.currentReachabilityStatus == .NotReachable {
    print("not connected")
} else {
    print("connected")
}

a bit safer? If the reachability object can't be created this wouldn't crash the app but gracefully report "not connected".

Thanks to ashleymills very much and sorry for late reply.
now the code has been updated and it's work for me very very well and specially appreciat the network notifier work very fast.

I do my work like that.
A) Simply net checking
1) write the below code in app delegate class

SSASwiftReachability.sharedManager?.startMonitoring()

2) check your network connectivity before request from web

if SSASwiftReachability.sharedManager?.isReachable() == true {
  print("YES CONNECTED")
}
else {
 print("NOT CONNECTED")
}

B) Observing network notifier
1) write the below code in app delegate class

SSASwiftReachability.sharedManager?.startMonitoring()

2) write the below code in viewDidLoad() method

NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityStatusChanged:", name: SSAReachabilityDidChangeNotification, object: nil)

3) Implement Notifier method like that its 100% work for me.

func reachabilityStatusChanged(notification: NSNotification) {

        if let info = notification.userInfo {

            if let status = info[SSAReachabilityNotificationStatusItem] {

                print(status.description)

                let  reachability = SSASwiftReachability.sharedManager

                switch reachability?.networkReachabilityStatus {

                case .ReachableViaWiFi?:
                    print(NetReachable.REACHABLEVIAWIFI)
                    break
                case .ReachableViaWWAN?:
                    print(NetReachable.REACHABLEVIAWWAN)
                    break
                case .Reachable?:
                    print(NetReachable.REACHABLE)
                    break
                case .NotReachable?:
                    print(NetReachable.NOTREACHABLE)
                    break
                default :
                    print(NetReachable.NOTREACHABLE)
                }
            }
        }
    }

@imran87,can you provide us with some example.Looks like your code got 2 way.
Any Help?Especially at B?Is this also work on cellular?.Please I really need example.

@imran87 ,Can you provide some example please.I really want to learn about that and I am beginner at swift.

Hey Guys, I made it work in my Swift project with the code below in my AppDelegate.swift file for reachabilityswift.

import ReachabilitySwift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

var reach: Reachability?

var window: UIWindow?        

    // Reachability code
    // Allocate a reachability object
    do {
    self.reach = try Reachability.reachabilityForInternetConnection()
    } catch {
      // Handle it 馃憤          
    }
    // Set the blocks
    self.reach!.whenReachable = {
        (let reach: Reachability!) -> Void in
        // keep in mind this is called on a background thread
        // and if you are updating the UI it needs to happen
        // on the main thread, like this:
        dispatch_async(dispatch_get_main_queue()) {
            print("REACHABLE!")
        }
    }

    self.reach!.whenUnreachable = {
        (let reach: Reachability!) -> Void in
        print("UNREACHABLE!")
    }
    do {
           try self.reach!.startNotifier()
    } catch {
      // Handle it 馃憤    
    }

    return true
}
Was this page helpful?
0 / 5 - 0 ratings