Giter Club home page Giter Club logo

reachability.swift's Introduction

Reachability.swift

Reachability.swift is a replacement for Apple's Reachability sample, re-written in Swift with closures.

It is compatible with iOS (8.0 - 12.0), OSX (10.9 - 10.14) and tvOS (9.0 - 12.0)

Inspired by https://github.com/tonymillion/Reachability

Supporting Reachability.swift

Keeping Reachability.swift up-to-date is a time consuming task. Making updates, reviewing pull requests, responding to issues and answering emails all take time.

Please consider sponsoring me https://github.com/sponsors/ashleymills, it's a great way to say thanks!

If you're an iOS developer who's looking for a quick and easy way to create App Store screenshots, please try out my app Screenshot Producer

Devices  Layout Copy Localize Export      

And don't forget to the repo. This increases its visibility and encourages others to contribute.

Thanks Ash

Got a problem?

Please read https://github.com/ashleymills/Reachability.swift/blob/master/CONTRIBUTING.md before raising an issue.

Installation

Manual

Just drop the Reachability.swift file into your project. That's it!

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. To install Reachability.swift with CocoaPods:

  1. Make sure CocoaPods is installed.

  2. Update your Podfile to include the following:

    use_frameworks!
    pod 'ReachabilitySwift'
  3. Run pod install.

  1. In your code import Reachability like so: import Reachability

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To install Reachability.swift with Carthage:

  1. Install Carthage via Homebrew
$ brew update
$ brew install carthage
  1. Add github "ashleymills/Reachability.swift" to your Cartfile.

  2. Run carthage update.

  3. Drag Reachability.framework from the Carthage/Build/iOS/ directory to the Linked Frameworks and Libraries section of your Xcode project’s General settings.

  4. Add $(SRCROOT)/Carthage/Build/iOS/Reachability.framework to Input Files of Run Script Phase for Carthage.

  5. In your code import Reachability like so: import Reachability

Swift Package Manager (SPM)

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. To integrate using Apple's Swift package manager from xcode :

  1. File -> Swift Packages -> Add Package Dependency...

  2. Enter package URL : https://github.com/ashleymills/Reachability.swift, choose the latest release

Example - closures

NOTE: All closures are run on the main queue.

//declare this property where it won't go out of scope relative to your listener
let reachability = try! Reachability()

reachability.whenReachable = { reachability in
    if reachability.connection == .wifi {
        print("Reachable via WiFi")
    } else {
        print("Reachable via Cellular")
    }
}
reachability.whenUnreachable = { _ in
    print("Not reachable")
}

do {
    try reachability.startNotifier()
} catch {
    print("Unable to start notifier")
}

and for stopping notifications

reachability.stopNotifier()

Example - notifications

NOTE: All notifications are delivered on the main queue.

//declare this property where it won't go out of scope relative to your listener
let reachability = try! Reachability()

//declare this inside of viewWillAppear

     NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
    do{
      try reachability.startNotifier()
    }catch{
      print("could not start reachability notifier")
    }

and

@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 .unavailable:
    print("Network not reachable")
  }
}

and for stopping notifications

reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)

Want to help?

Got a bug fix, or a new feature? Create a pull request and go for it!

Let me know!

If you use Reachability.swift, please let me know about your app and I'll put a link here… and tell your friends!

Cheers, Ash

reachability.swift's People

Contributors

abizern avatar abunur avatar adityatrivedi avatar amarcadet avatar ashleymills avatar bgreenlee avatar bm-w avatar bsstm8 avatar carlhunterroach avatar connorpower avatar corteggo avatar damonjones avatar daniarnaout avatar dannymout avatar delannoyk avatar drichardson avatar dstorm-fl avatar elegyd avatar gaudecker avatar hamchapman avatar jcesarmobile avatar mokagio avatar mugunthkumar avatar p4checo avatar plashchynski avatar raburski avatar rgoble4 avatar tommyming avatar uny avatar zummenix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reachability.swift's Issues

Reachability crashes sometime for iOS 7 and 8

This is the error report I am getting from fabric:
Reachability.swift line 0
partial apply forwarder for imDown.Reachability.(startNotifier (imDown.Reachability) -> () -> Swift.Bool).(closure #1)

and here is the code I am using:

    let reachability = Reachability.reachabilityForInternetConnection()
    NSNotificationCenter.defaultCenter().addObserver(self,selector: Selector("handleNetworkChange:"),name: ReachabilityChangedNotification, object: reachability)

    reachability.startNotifier()

    if !reachability.isReachable() && !self.isShowingNetworkAlert{
        println("Not reachable")
        self.isShowingNetworkAlert = true
        UIApplication.sharedApplication().keyWindow?.rootViewController?.presentIMDAlertWith(title: "CAN'T CONNECT", subtitle: "", body: "Check network connection and try again.", confirmation: "Sounds good!", completionHandler: {self.isShowingNetworkAlert = false})
    }

isReachable() doesn't work

The timer works, but because there can be a delay of up to 5 seconds I do a manual check using isReachable() when the user tries to access the net in my app. However isReachable() will return TRUE even if I have just turned off WIFI. Does isReachable() do an instant check of connectivity or does it only give a correct result after the timer fires?

previousFlags private property?

Hi, how can i know previous states of reachability (without saving it locally) in reachabilityChanged notification handler?
'previousFlags' property is private even though its marked under public properties (mistake?)

Network Lost

If any service is running and lock device in this period then network lost message is coming.
Thanks,

iOS 7 support

Any chance of supporting iOS 7? A quite large share of our user base still uses it.

Thanks,

about bugs: 0xA9FE0000

about bugs: 0xA9FE0000
xcode will show this error: Integer literal overflows when stored into 'Int'

fixed in this way:

change row 102

    localWifiAddress.sin_addr.s_addr = in_addr_t(Int64(0xA9FE0000).bigEndian)

to:
var iDef: __uint32_t = 0xA9FE0000
localWifiAddress.sin_addr.s_addr = in_addr_t(iDef)

License disproportionately restrictive

I was curious if you meant to include such a restrictive license? Considering the fact that this is a port of a port from Apple, I'd expect a very unrestrictive license (MIT, Apache). I truly appreciate the work you put into it and am very grateful that you shared it. The license requirements make it something that has to be checked by legal and, therefore, quite expensive (of course, none of that cost goes to you, sadly).

Would you consider a more liberal license? I'd much rather contribute back to this project with any future fixes that might come along and I'd bet that others share my sentiment.

Reachability Crashes within iPhone 5 (v8.3) Simulation

Environment: Xcode 6.3
File: Reachability.swift, line #102....

I get the following compile crash within iPhone 5 simulation:
"Integer literal overflows when stored into 'Int':
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as! 169.254.0.0
localWifiAddress.sin_addr.s_addr = in_addr_t(Int(0xA9FE0000).bigEndian)

The compiler points to '0xA9FE000' as the source of the error.

Note: this doesn't occur within IPhone 6 simulation.

Doesn't work

Add Reachability.swift to my project and tried both closure code and notification code, but it does not work. Test project doesn't work either.

Reachability doesn't work when stored as a static property

Maybe it's me who don't understand some run-time subtleties, but could you please explain me why the following code doesn't work? It compiles, but notification do not work. Thanks in advance.

private static let reachability: Reachability? = {
    let reachability: Reachability
    do {
        reachability = try Reachability.reachabilityForInternetConnection()
    } catch {
        print("Unable to create Reachability")
        return nil
    }

    reachability.whenReachable = { reachability in
        // this is called on a background thread, but UI updates must
        // be on the main thread, like this:
        dispatch_async(dispatch_get_main_queue()) {
            if reachability.isReachableViaWiFi() {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
        }
    }
    reachability.whenUnreachable = { reachability in
        // this is called on a background thread, but UI updates must
        // be on the main thread, like this:
        dispatch_async(dispatch_get_main_queue()) {
            print("Not reachable")
        }
    }

    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }

    return reachability
}()

Using pod of Reachability getting error

Hi
I'm using Reachability class using cocoapods but when I add following line in my Podfile

pod 'ReachabilitySwift', git: 'https://github.com/ashleymills/Reachability.swift'

and run pod update command in terminal. the pod successfully added in my project but when I used
import Reachability

in my controller Xcode give me error like that image (https://cloudup.com/cltJbfDwO3K). I'm using Xcode 6.4 and CocoaPods 0.38
Please give solution of that asap.
Thanks in advance

swift2

The library is not working with swift 2, many errors.

Reachability Notification

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 it didn't work for me please somebody help quickly

here my system version is OS X El Capitan version 10.11.2
and xcode 7.2

"Use Cellular Data" turned off is reported incorrectly as reachable

Turning off "Use Cellular Data" specifically for one application, is still reported by the Reachability class as reachable, despite not being able to load data from a remote server.

For example, using a UIWebView and having "Use Cellular Data" off does not load a remote URL and falls into the delegate function didFailLoadWithError, the code being NSURLErrorNotConnectedToInternet. However, the same view controller will report isReachable() as true.

This may yet not be able to be resolved without changes from Apple.

Error during `pod install`

Hey I have this error when I do pod install . Any idea what is wrong?

[!] Unable to find a specification for 'ReachabilitySwift'.

[!] Unable to load a podspec from `ReachabilitySwift.podspec`, skipping:

Pod::DSLError

Behaviour on test

Hi I have written a Wrapper-class and a unit test and recognizes a strange behaviour under test (some kind of Volkswagening?). Under test the lib tells me, that it can reach an invalid URL. Running on simulator with an invalid URL it tells me, that the host can not be reached under Wifi but under Cellular.

Here is my wrapper with an invalid host:

import Foundation
import ReachabilitySwift

class ReachabilityHelper: NSObject {

    var isOnline = false
    private var reachability: Reachability


    override init() {

        self.reachability = try! Reachability(hostname: "anInvalidUrl")

        super.init()
        start()
    }


    private func start(){

        self.reachability.whenReachable = { reachability in

            dispatch_async(dispatch_get_main_queue()) {

                self.isOnline = true

                if reachability.isReachableViaWiFi() {
                    print("Reachable via WiFi")
                } else {
                    print("Reachable via Cellular")
                }
            }
        }
        self.reachability.whenUnreachable = { reachability in

             self.isOnline = false

            dispatch_async(dispatch_get_main_queue()) {
                print("Not reachable")
            }
        }

        do {
            try self.reachability.startNotifier()


            if(isReachable()){
                print("server is reachable")
            }
            else{
                print("server is not reachable")
            }

        } catch {
            print("Unable to start notifier")
        }
    }

    func isReachable()->Bool{

        self.isOnline =  self.reachability.isReachable()
        return self.isOnline
    }


    //MARK: - SharedInstance
    class var sharedInstance: ReachabilityHelper {
        struct Singleton {
            static let instance = ReachabilityHelper()
        }
        return Singleton.instance
    }

}

And here my test:

class ReachabilityHelperTest: XCTestCase {

    override func setUp() {
        super.setUp()
        ReachabilityHelper.sharedInstance
    }


    func testServerIsReachable() {
        let isReachable = ReachabilityHelper.sharedInstance.isReachable()

        XCTAssertTrue(isReachable)
    }
}

Simpler usage?

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 ?

Crash on uk.co.joylordsystems.reachability_timer_queue

Hello,

I have following crash in my crashlytics logs:

Crashed: uk.co.joylordsystems.reachability_timer_queue
EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x00000004

Thread : Crashed: uk.co.joylordsystems.reachability_timer_queue
0 libswiftCore.dylib 0x0091b254 _ZL40usesNativeSwiftReferenceCounting_unownedPKv + 95
1 libswiftCore.dylib 0x0091b2f5 swift_unknownWeakRetain + 84
2 libswiftCore.dylib 0x0091b2f5 swift_unknownWeakRetain + 84
3 MyProject 0x000fdf68 partial apply forwarder for MyProject.Reachability.(startNotifier (MyProject.Reachability) -> () -> Swift.Bool).(closure #1) (Reachability.swift)
4 libdispatch.dylib 0x3af883ef _dispatch_source_invoke + 262
5 libdispatch.dylib 0x3af8bc71 _dispatch_queue_drain + 412
6 libdispatch.dylib 0x3af88c6f _dispatch_queue_invoke + 42
7 libdispatch.dylib 0x3af8c5f1 _dispatch_root_queue_drain + 76
8 libdispatch.dylib 0x3af8c8dd _dispatch_worker_thread2 + 56
9 libsystem_pthread.dylib 0x3b0b7c17 _pthread_wqthread + 298


Hope you can help about the problem.

Failable inits / throws

In the develop branch, I've clarified which init methods are failable, made the class methods "throws" along with startNotifier() and updated the README. Would be great if people could check this out and make sure I haven't made a mess of it!

Thanks
Ash

WatchOS 2.0

Hi,

When I try to add ReachabilitySwift via cocoapods on my project I get this error:

(watchOS 2.0) is not compatible with ReachabilitySwift (2.1), which does not support watchos

Podfile :
target 'MyApp Extension' do

platform :watchos, '2.0'

pod 'ReachabilitySwift', '~> 2.1'

end

do you know how to fix it ?

Best Regards

Add watchOS and tvos to podspec

ReachabilitySwift should be able to support watchOS and TVOS.
Just add these lines to the .podspec:

s.watchos.deployment_target = '2.0'
s.tvos.deployment_target = '9.0'

在连接WIFI的情况下检测

在连接WIFI的情况,且用户所连接的WIFI是局域网而非广域网。服务器连接超时等检测没有好的解决方案吗?

Connection status will be delayed five seconds

Hi Ashley, thank you for providing such a good tool

The use of some questions to ask you

I found that switching from wifi to no connection, it will delay for about 5 seconds

Will return "No Connection"

Within five seconds, the connection status has been returned "WiFi"

Cellular will not be the case, is this normal?

Notifications on Main thread or no?

In the README, you state that the notifications are delivered on the main thread, but startNotifier posts the notification on a different thread at least once:

public func startNotifier() throws {

  // ...

  // Perform an intial check
  dispatch_async(reachabilitySerialQueue) { () -> Void in
      let flags = self.reachabilityFlags
      self.reachabilityChanged(flags)
  }

  // ...
}

I noticed that the callback passed to SCNetworkReachabilitySetCallback does call reachabilityChanged on the main thread.

Is the README wrong? Am I meant to be dispatching async to the main queue in my notification handler?

Thanks!

TV OS compatibility

Hi there,

Is the code compatible with TV OS? If yes, would it be possible to update the podspec and push it to cocoapods' spec repo?

If you don't have time, please let me know and I can create a pull request and/or (with your permission) push the new spec to the main spec repo.

Check on app startup if internet available.

Hello sir,

I managed to create a very nice functionality in my app when the network status changes. But somehow I can't check for this when the app starts up. Is there a nice way to do this in AppDelegate? it looks like this right now.

 let reachability = Reachability.reachabilityForInternetConnection()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: "reachabilityChanged:",
        name: ReachabilityChangedNotification,
        object: reachability)
        reachability?.startNotifier()
}

Carthage installation problem

I still have problem with adding Reachability via Carthage. I get this error:

Dependency "Reachability.swift" has no shared framework schemes for any of the platforms: iOS

I've updated brew and other things. Where could be problem? Thanks

Reachability detecting cellular network (not cellular data)?

Can Reachability be used to detect if device is connected to any cellular network, so not if it has cellular data, but if it's connected to carrier?

I just want to detect when there is No Service message in top left instead of carrier name.

Thank you

Unable to access Reachability/Develop via Podfile

$~/workarea/Bliss (DevelopRic):pod install
Analyzing dependencies

CocoaPods 0.38.0.beta.2 is available.
To update use: sudo gem install cocoapods --pre
[!] This is a test version we'd love you to try.

Here's my Podfile:

pod 'Parse'
use_frameworks!

pod 'ReachabilitySwift', git: 'https://github.com/ashleymills/Reachability.swift'

Using Develop Branch for Xcode 7/Swift 2.0:

pod 'ReachabilitySwift', git: 'https://github.com/ashleymills/Reachability.swift/tree/develop'
...

...

For more information see http://blog.cocoapods.org
and the CHANGELOG for this version http://git.io/BaH8pQ.

Pre-downloading: ReachabilitySwift from https://github.com/ashleymills/Reachability.swift/tree/develop

[!] Error installing ReachabilitySwift
[!] /usr/local/bin/git clone https://github.com/ashleymills/Reachability.swift/tree/develop /var/folders/6w/fl6bb2fs2kdfbfxd2hz0cjr40000gn/T/d20150714-3515-kn5q7m --single-branch --depth 1

Cloning into '/var/folders/6w/fl6bb2fs2kdfbfxd2hz0cjr40000gn/T/d20150714-3515-kn5q7m'...

fatal: repository 'https://github.com/ashleymills/Reachability.swift/tree/develop/' not found

App Crashing in Production Mode

  • App crashing in Adhoc .ipa file after using Swift 1.1 code and Reachability.swift code. Its working fine in Development of app through Xcode but .ipa created resulting crashing.

Spelling error (cosmetic only)

line 36: public type alias NetworkUneachable = ...

I think you mean "Unreachable" (note the 'r')

Not a big problem, but a bit disconcerting to have it so prominent...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.