Connectivity

repository·main·Indexed 23 days ago

https://github.com/rwbutler/connectivity

An iOS framework that wraps Apple's Reachability to provide reliable Internet connectivity detection. It specifically addresses the 'captive portal' problem by contacting endpoints to distinguish between a connected network interface and actual Internet access. It supports monitoring via callbacks, Combine, and synchronous checks, and can be installed via CocoaPods, Carthage, or Swift Package Manager.

Tokens
3.9K
Snippets
13
Records
25
Agent score
33%

What's inside Connectivity

  1. What is Connectivity and how does it solve the captive portal problem?

    main

    Connectivity is a wrapper for Apple's Reachability. While Reachability only indicates if a network interface is available (e.g., Wi-Fi is on), it cannot detect if that interface actually provides Internet access.

    Connectivity solves the captive portal problem (where a device is connected to a Wi-Fi network that requires user registration/login before granting Internet access). It achieves this by replicating the mechanism iOS uses: contacting specific endpoints and checking if the response contains a specific success indicator (like the word Success). If a captive portal intercepts the request and returns a login page instead, Connectivity detects that the expected success indicator is missing and reports a lack of Internet connectivity.

  2. How Connectivity works internally

    main

    Connectivity works by contacting a set of endpoints to determine if true Internet connectivity is present.

    • Detection Mechanism: It checks if endpoints return a specific HTML response (e.g., containing the word Success). If a captive portal intercepts the connection, the response will be a login page instead, and the check will fail.
    • Endpoints: By default, it uses endpoints similar to those used by iOS. Developers can customize this by appending to the connectivityURLs property.
    • Success Threshold: The successThreshold property determines the percentage of contacted endpoints that must succeed to conclude connectivity is present. The default is 50% (meaning if 2 URLs are checked, at least 1 must succeed).
    • Lifecycle: Developers use startNotifier() to begin monitoring and stopNotifier() to stop. Connectivity provides a status property for synchronous checks and posts Notification.Name.ConnectivityDidChange to NotificationCenter for asynchronous updates.
  3. Install Connectivity via Carthage

    main

    To integrate Connectivity into your project via Carthage, add the following line to your Cartfile:

    github "rwbutler/Connectivity"

    From the macOS Terminal, run the following command to build the framework:

    carthage update --platform iOS

    After the build completes, drag Connectivity.framework into your Xcode project.

  4. Install OHHTTPStubs via CocoaPods

    main

    CocoaPods is the recommended installation method. Choose the subspec based on your language:

    • Objective-C only: pod 'OHHTTPStubs'
    • Swift: pod 'OHHTTPStubs/Swift' (includes NSURLSession, JSON, and Swiftier API wrappers)

    Available subspecs:

    • Default: Includes NSURLSession, JSON, and OHPathHelpers.
    • Swift: Adds the Swiftier API.
    • HTTPMessage & Mocktail: Opt-in subspecs for specific formats.
    • OHPathHelpers: Can be used independently.
    pod 'OHHTTPStubs/Swift'
  5. Enable connectivity polling

    main

    If you need to be constantly apprised of changes and don't want to rely solely on Reachability state changes, you can enable polling. When enabled, Connectivity will poll the configured connectivityURLs every pollingInterval seconds (default is 10).

    To enable:

    1. Set isPollingEnabled = true.
    2. Call startNotifier().
    connectivity.isPollingEnabled = true
    connectivity.startNotifier()
  6. Manage stubs in unit tests

    main

    When using OHHTTPStubs in unit tests, follow these best practices to avoid side effects:

    1. Cleanup: Always remove stubs after each test to prevent them from leaking into subsequent test cases. Call [HTTPStubs removeAllStubs] in your tearDown method.
    2. Asynchronicity: Ensure you wait for the request to receive its response before performing assertions and finishing the test case.
  7. App Store submission guidelines for OHHTTPStubs

    main

    You can use OHHTTPStubs in apps submitted to the App Store as it does not use any private APIs.

    However, since stubs are typically intended for development or testing, it is recommended to ensure they do not leak into production. To prevent your production app from hitting stubs instead of the real network, use one of the following strategies:

    • Include OHHTTPStubs only in your test targets.
    • Wrap usage inside #if DEBUG blocks.
    • Use per-Build-Configuration pods in CocoaPods to ensure the library is only present in development builds.
  8. Monitor connectivity changes using callbacks

    main

    To observe real-time changes in internet connectivity, instantiate a Connectivity object and assign closures to whenConnected and whenDisconnected. You must call startNotifier() to begin listening and stopNotifier() when you no longer need updates.

    Important: You must maintain a strong reference to the Connectivity instance (e.g., as an instance variable) for the duration of its use to ensure callbacks are received.

    let connectivity: Connectivity = Connectivity()
    
    let connectivityChanged: (Connectivity) -> Void = { [weak self] connectivity in
         self?.updateConnectionStatus(connectivity.status)
    }
    
    connectivity.whenConnected = connectivityChanged
    connectivity.whenDisconnected = connectivityChanged
    
    // Start listening
    connectivity.startNotifier()
    
    // ... later
    connectivity.stopNotifier()
  9. Install Connectivity via Swift Package Manager

    main

    To add Connectivity to your Xcode project using Swift Package Manager:

    1. Open your project in Xcode.
    2. Select File > Swift Packages > Add Package Dependency.
    3. Enter the following repository URL: https://github.com/rwbutler/connectivity
    4. Select your preferred versioning rule (branch, commit, or versioned release).
    5. When prompted to select package products, ensure Connectivity is selected and your main app target is chosen in the rightmost column.
    6. Click Finish to complete the integration.