Replacement for Apple's Reachability re-written in Swift with closures

Overview

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

Comments
  • app get rejected because of ipv6 issue

    app get rejected because of ipv6 issue

    hi! i created one iOS app with swift programming it get rejected 4 time because of ipv6 problem m not sure that it is because of Network-Reachabilty. m also using alamofire , and is also has network rateability class today i checked with breakpoint but its not going there its checking internet connectivity only with NetworkReachability. any solution or any idea why my app is getting rejected.

    they send me this

    Performance - 2.1

    We discovered one or more bugs in your app when reviewed on the iPhone running iOS 9.3.2 on Wi-Fi.

    Specifically, we were still unable to login to the app.

    We've attached screenshots for your reference.

    Next Steps

    Please run your app on a device to identify the issue(s), then revise and resubmit your app for review.

    Apps are reviewed on an IPv6 network. Please ensure that your app supports IPv6 networks, as IPv6 compatibility is required.

    For additional information about supporting IPv6 Networks, please refer to Supporting IPv6 DNS64/NAT64 Networks and Supporting IPv6-only Networks.

    For a networking overview, see About Networking.

    If we misunderstood the intended behaviour of your app, please reply to this message in Resolution Center to provide information on how these features were intended to work.

    For new apps, uninstall all previous versions of your app from a device, then install and follow the steps to reproduce the issue(s). For updates, install the new version as an update to the previous version, then follow the steps to reproduce the issue(s).

    SOLVED! 
    opened by Aishly 22
  • No such module 'ReachabilitySwift

    No such module 'ReachabilitySwift

    Hello,

    i am using xcode 9.1 and swift 3.2 always getting an error:

    No such module 'ReachabilitySwift

    in podfile: pod 'ReachabilitySwift'

    kindly let me know what can i do ... always getting an error

    opened by mohamamdkalim 18
  • ReachabilitySwift 3.0 doesn't update with Cocoapods

    ReachabilitySwift 3.0 doesn't update with Cocoapods

    I've updated XCode 8.0 with Swift 3, and I can't update ReachabilitySwift 3.0

    [!] Unable to satisfy the following requirements:

    • ReachabilitySwift (~> 3) required by Podfile

    None of your spec sources contain a spec satisfying the dependency: ReachabilitySwift (~> 3).

    You have either:

    • out-of-date source repos which you can update with pod repo update.
    • mistyped the name or version.
    • not added the source repo that hosts the Podspec to your Podfile.

    Note: as of CocoaPods 1.0, pod repo update does not happen on pod install by default.

    opened by davilinho 16
  • Reachability crashes sometime for iOS 7 and 8

    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})
        }
    
    opened by aTylerRice 16
  • Swift 3 / iOS 10

    Swift 3 / iOS 10

    Please check out the ios10 feature branch (https://github.com/ashleymills/Reachability.swift/tree/feature/ios10) which has been updated to Swift 3

    Please log any issues and create PRs to that branch

    enhancement help wanted 
    opened by ashleymills 13
  • Using Cocoapods to install Reachability 4.0 doesn't work

    Using Cocoapods to install Reachability 4.0 doesn't work

    Hey, after I updated Cocoapods and the repos (pod repo update), I was unable to install Reachability :(.

    I tried: pod 'ReachabilitySwift' and pod 'ReachabilitySwift' , '~> 3.0'

    the response:

    [!] Error installing ReachabilitySwift
    [!] /usr/bin/git clone https://github.com/ashleymills/Reachability.swift.git /var/folders/1w/rbhn9wvn2qn6dghyrq6zmf5r0000gn/T/d20170923-60074-q1ic10 --template= --single-branch --depth 1 --branch v3
    
    Cloning into '/var/folders/1w/rbhn9wvn2qn6dghyrq6zmf5r0000gn/T/d20170923-60074-q1ic10'...
    warning: Could not find remote branch v3 to clone.
    fatal: Remote branch v3 not found in upstream origin
    

    And after i've read the README again, i founded the Warning, that ReachabilitySwift has been renamed to Reachability. So I tried pod 'Reachability' but this installs a definitely other Repo with versionnumber 3.2 written in Obj-C.

    What did I wrong? tjarbo :)

    opened by tjarbo 12
  • DSL Error with Cocoapods 1.0.0.beta.4

    DSL Error with Cocoapods 1.0.0.beta.4

    Podfile (simplified a bit)

    source 'https://github.com/CocoaPods/Specs.git'
    use_frameworks!
    platform :ios, '8.0'
    
    pod 'ReachabilitySwift', git: 'https://github.com/ashleymills/Reachability.swift'
    

    I receive

    [!] Unable to find a specification for 'ReachabilitySwift'.
    
    [!] Unable to load a podspec from `ReachabilitySwift.podspec`, skipping:
    
    Pod::DSLError
    

    I just upgraded to 1.0.0.beta.4, and everything was working for in 0.39.0, so I guess their required format changed?

    opened by bclymer 12
  • Crash on uk.co.joylordsystems.reachability_timer_queue

    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.

    opened by gunhansancar 11
  • from Objective-c class - use of undeclared identifier 'Reachability'

    from Objective-c class - use of undeclared identifier 'Reachability'

    Before version 3 I could use Reachibility class within objc code.

    now, I get this error. I install with Cocoapods 1.0.1, use

    @import ReachabilitySwift; in my .m file but it fails to compile.

    enhancement 
    opened by mime29 10
  • Simpler usage?

    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 ?

    Documentation 
    opened by cannyboy 9
  • Is it possible to check if WiFi is connected but there is no internet connection?

    Is it possible to check if WiFi is connected but there is no internet connection?

    I don't know if this is possible but here's my question -

    1. When the WiFi is connected & the internet is ON then Yellow Light glows on Router
    2. When the WiFi is connected & the Internet is OFF then Red Light glows on Router

    So is it possible to distinguish the 2nd case or is it just the same as when Internet is not reachable?

    opened by deadcoder0904 7
  • Reachability could not detect cellular network on iOS version 14.8.1

    Reachability could not detect cellular network on iOS version 14.8.1

    reachability could not be detected when we are on cellular network it says network is unreadable, tested on safari it is working fine, but reachability class won't give any indication for network, this is particularly coming on iOS version 14.8.1, please could you check this once.

    opened by gurpalrajput 0
  • xCode13 issue

    xCode13 issue

    Hi Guys,

    I use this library on Carthage and I have this issue on xcode13

    Failed to build module 'Reachability'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 5.4 (swiftlang-1205.0.26.9 clang-1205.0.19.55)', while this compiler is 'Apple Swift version 5.5 (swiftlang-1300.0.31.1 clang-1300.0.29.1)'). Please select a toolchain which matches the SDK.

    Thank you

    J

    opened by pjcau 1
  • fix: don't build for distribution to avoid .swiftinterface bugs

    fix: don't build for distribution to avoid .swiftinterface bugs

    This avoids https://bugs.swift.org/browse/SR-14195. Right now, building with module stability doesn't actualy provide any benefits to the project; as soon as you are in a situation where the .swiftinterface actually gets used, it's invalid.

    An alternative fix here would be to rename the class, but that is a larger breaking change.

    opened by thedavidharris 0
  • Query around connections under other interfaces i.e. USB, Bluetooth, etc

    Query around connections under other interfaces i.e. USB, Bluetooth, etc

    Does Reachability (or Apple's frameworks for that matter) allow us to distinguish whether a connection is via USB, Bluetooth, etc? Does Reachability only actually distinguish between cellular vs non-cellular but it calls non-cellular wifi?

    opened by ptrkstr 0
Releases(v5.1.0)
Owner
Ashley Mills
Highly experienced London based Swift and Objective C iOS developer.
Ashley Mills
We need to observe the REAL reachability of network. That's what RealReachability do.

RealReachability We need to observe the REAL reachability of network for iOS. That's what RealReachability do. Why RealReachability? As we know, we al

Zhenwei Guan 3.1k Dec 13, 2022
Swift Express is a simple, yet unopinionated web application server written in Swift

Documentation <h5 align="right"><a href="http://demo.swiftexpress.io/">Live ?? server running Demo <img src="https://cdn0.iconfinder.com/data/icons/

Crossroad Labs 850 Dec 2, 2022
Easy to use OAuth 2 library for iOS, written in Swift.

Heimdallr Heimdallr is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant f

trivago N.V. 628 Oct 17, 2022
Network abstraction layer written in Swift.

Moya 14.0.0 A Chinese version of this document can be found here. You're a smart developer. You probably use Alamofire to abstract away access to URLS

Moya 14.4k Jan 1, 2023
OAuth2 framework for macOS and iOS, written in Swift.

OAuth2 OAuth2 frameworks for macOS, iOS and tvOS written in Swift 5.0. ⤵️ Installation ?? Usage ?? Sample macOS app (with data loader examples) ?? Tec

Pascal Pfiffner 1.1k Jan 8, 2023
A generic network layer written in swift

SwiftyNet 1.0.0 A generic network layer written in swift. you can use it as an abstraction layer above Alamofire with generic returned types. Installa

Mohamed Salah Zidane 17 Oct 11, 2021
Tiny http server engine written in Swift programming language.

What is Swifter? Tiny http server engine written in Swift programming language. Branches * stable - lands on CocoaPods and others. Supports the latest

null 3.6k Dec 31, 2022
MQTT for iOS and macOS written with Swift

CocoaMQTT MQTT v3.1.1 client library for iOS/macOS/tvOS written with Swift 5 Build Build with Xcode 11.1 / Swift 5.1 Installation CocoaPods Install us

EMQ X MQTT Broker 1.4k Jan 1, 2023
Http Request wrapper written in Swift

Net Net is a HttpRequest wrapper written in Swift Features GET, POST, PUT, DELETE method Powerful request params: nested params, number, string, dic,

Le Van Nghia 304 Jun 29, 2022
A simple GCD based HTTP client and server, written in 'pure' Swift

SwiftyHTTP Note: I'm probably not going to update this any further - If you need a Swift networking toolset for the server side, consider: Macro.swift

Always Right Institute 116 Aug 6, 2022
DispatchSource based socket framework written in pure Swift

SwiftDSSocket Overview SwiftDSSocket is a purely swift based asynchronous socket framework built atop DispatchSource. Function signatures are pretty m

Yi Huang 65 Nov 15, 2022
A simple HTTP server written in Swift

http4swift http4swift is a tiny HTTP server library for Nest-compatible applications. This project is unstable, and the API might be changed at anytim

Shun Takebayashi 27 Jun 29, 2022
WebSocket(RFC-6455) library written using Swift

DNWebSocket Object-Oriented, Swift-style WebSocket Library (RFC 6455) for Swift-compatible Platforms. Tests Installation Requirements Usage Tests Conf

Gleb Radchenko 36 Jan 29, 2022
RSNetworking is a networking library written entirly for the Swift programming language.

RSNetworking is a networking library written entirly for the Swift programming language.

null 18 Feb 25, 2018
iOS Network monitor/interceptor framework written in Swift

NetShears NetShears is a Network interceptor framework written in Swift. NetShears adds a Request interceptor mechanisms to be able to modify the HTTP

Divar 119 Dec 21, 2022
📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.

Apollo iOS is a strongly-typed, caching GraphQL client, written in Swift. It allows you to execute queries and mutations against a GraphQL server, and

Apollo GraphQL 3.6k Jan 7, 2023
Lightweight, flexible HTTP server framework written in Swift

Hummingbird Lightweight, flexible server framework written in Swift. Hummingbird consists of three main components, the core HTTP server, a minimal we

Hummingbird 245 Dec 30, 2022
ServiceData is an HTTP networking library written in Swift which can download different types of data.

ServiceData Package Description : ServiceData is an HTTP networking library written in Swift which can download different types of data. Features List

Mubarak Alseif 0 Nov 11, 2021
AsyncHTTP - Generic networking library written using Swift async/await

Generic networking library written using Swift async/await

Laszlo Teveli 7 Aug 3, 2022