### Install Carthage Source: https://github.com/rwbutler/connectivity/blob/main/README.md Commands to install the Carthage dependency manager using Homebrew. Update Homebrew first. ```bash brew update brew install carthage ``` -------------------------------- ### Add Connectivity to Podfile Source: https://github.com/rwbutler/connectivity/blob/main/README.md Include this line in your Podfile to add the Connectivity library as a dependency. Then run 'pod install'. ```ruby pod "Connectivity" ``` -------------------------------- ### Install CocoaPods Source: https://github.com/rwbutler/connectivity/blob/main/README.md Use this command to install the CocoaPods dependency manager. Ensure Ruby gems are set up. ```bash gem install cocoapods ``` -------------------------------- ### Start and Stop Network Monitoring Source: https://context7.com/rwbutler/connectivity/llms.txt Use `startNotifier` to begin observing network interface changes and `stopNotifier` to end monitoring. Configure polling intervals and preferred frameworks. ```swift import Connectivity class AppDelegate: UIResponder, UIApplicationDelegate { private let connectivity = Connectivity() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Configure optional settings connectivity.isPollingEnabled = true connectivity.pollingInterval = 10.0 // Check every 10 seconds connectivity.pollWhileOfflineOnly = true // Only poll when offline connectivity.framework = .network // Use Network framework (iOS 12+) // Set up callbacks connectivity.whenConnected = { [weak self] connectivity in self?.handleConnected(connectivity) } connectivity.whenDisconnected = { [weak self] connectivity in self?.handleDisconnected(connectivity) } // Start monitoring on main queue (default) connectivity.startNotifier(queue: .main) return true } func applicationWillTerminate(_ application: UIApplication) { connectivity.stopNotifier() } private func handleConnected(_ connectivity: Connectivity) { NotificationCenter.default.post(name: .internetAvailable, object: nil) } private func handleDisconnected(_ connectivity: Connectivity) { NotificationCenter.default.post(name: .internetUnavailable, object: nil) } } extension Notification.Name { static let internetAvailable = Notification.Name("internetAvailable") static let internetUnavailable = Notification.Name("internetUnavailable") } ``` -------------------------------- ### Start Connectivity Notifications Source: https://github.com/rwbutler/connectivity/blob/main/README.md Call `startNotifier()` to begin receiving connectivity change notifications. Remember to call `stopNotifier()` when finished to prevent memory leaks. ```swift connectivity.startNotifier() ``` -------------------------------- ### Configure Connectivity Polling Interval Source: https://github.com/rwbutler/connectivity/blob/main/README.md Set the polling interval for connectivity checks directly on the `Connectivity` object. This example sets the interval to 5 seconds. ```swift let connectivity = Connectivity() connectivity.pollingInterval = 5 connectivity.expectedResponseString = "Success" connectivity.validationMode = .containsExpectedResponseString ``` -------------------------------- ### Automatic Loading for Custom NSURLSession Configurations Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md OHHTTPStubs uses method swizzling to automatically load and install for `NSURLSession` instances created with default or ephemeral configurations. This is the relevant code section. ```Objective-C + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self swizzleMethodlist]; }); } ``` -------------------------------- ### Configure Connectivity with Fluent API Source: https://context7.com/rwbutler/connectivity/llms.txt Customize Connectivity behavior using a fluent API for URLs, polling, response validation, URL session, bearer tokens, and the underlying framework. Start monitoring after configuration. ```swift import Connectivity // Create a fully configured Connectivity instance using fluent API let configuration = ConnectivityConfiguration() .configureConnectivity(urls: [ URL(string: "https://www.apple.com/library/test/success.html")!, URL(string: "https://example.com/connectivity-check")! ]) .configurePolling(isEnabled: true, interval: 15.0, offlineOnly: true) .configureResponseValidation(.containsExpectedResponseString, expected: "Success") .configureURLSession(.default) .configureBearerToken(with: "your-auth-token") .configureFramework(.network) let connectivity = Connectivity(configuration: configuration) connectivity.whenConnected = { conn in print("Internet is available: \(conn.status)") } connectivity.startNotifier() ``` -------------------------------- ### Automatic Loading for NSURLConnection and Shared NSURLSession Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md OHHTTPStubs automatically loads and installs for requests made using `NSURLConnection` or `[NSURLSession sharedSession]`. This code snippet illustrates the mechanism. ```Objective-C stubRequests || [HTTPStubs isEnabled]; if (!stubRequests) return NO; // If we are here, it means that stubbing is enabled, and we should intercept the request. return YES; ``` -------------------------------- ### Set Custom Connectivity URLs Source: https://github.com/rwbutler/connectivity/blob/main/README.md Specify custom URLs for connectivity checks by assigning an array of `URL` objects to the `connectivityURLs` property before starting notifications. ```swift connectivity.connectivityURLs = [URL(string: "https://www.apple.com/library/test/success.html")!] ``` -------------------------------- ### Perform One-Off Connectivity Check Source: https://context7.com/rwbutler/connectivity/llms.txt Use `checkConnectivity` for a single check without starting continuous monitoring. The completion handler provides detailed status, including specific connection types and whether Internet access is available. ```swift import Connectivity let connectivity = Connectivity() // One-off connectivity check connectivity.checkConnectivity { connectivity in switch connectivity.status { case .connected: print("Connected (interface unknown)") case .connectedViaWiFi: print("Connected via WiFi with Internet access") case .connectedViaCellular: print("Connected via Cellular with Internet access") case .connectedViaEthernet: print("Connected via Ethernet with Internet access") case .connectedViaWiFiWithoutInternet: print("WiFi connected but no Internet (captive portal?)") case .connectedViaCellularWithoutInternet: print("Cellular connected but no Internet") case .connectedViaEthernetWithoutInternet: print("Ethernet connected but no Internet") case .notConnected: print("No network connection") case .determining: print("Checking connectivity...") } // Check specific connection types if connectivity.isConnectedViaWiFi { print("WiFi is available with Internet") } if connectivity.isConnectedViaCellular { print("Cellular is available with Internet") } if connectivity.isConnectedViaWiFiWithoutInternet { print("WiFi without Internet - may need to authenticate") } } ``` -------------------------------- ### Stub Network Requests Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md Intercepts network requests based on a condition and returns a local file as the response. Use these examples to mock API endpoints during unit testing. ```objc [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.host isEqualToString:@"mywebservice.com"]; } withStubResponse:^HTTPStubsResponse*(NSURLRequest *request) { // Stub it with our "wsresponse.json" stub file (which is in same bundle as self) NSString* fixture = OHPathForFile(@"wsresponse.json", self.class); return [HTTPStubsResponse responseWithFileAtPath:fixture statusCode:200 headers:@{@"Content-Type":@"application/json"}]; }]; ``` ```swift stub(condition: isHost("mywebservice.com")) { _ in // Stub it with our "wsresponse.json" stub file (which is in same bundle as self) let stubPath = OHPathForFile("wsresponse.json", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"]) } ``` -------------------------------- ### Set Success Threshold for Connectivity Source: https://github.com/rwbutler/connectivity/blob/main/README.md Set the percentage of successful connections required to be deemed successfully connected. For example, 75% means three out of four checks must succeed. ```swift connectivity.successThreshold = Connectivity.Percentage(75.0) ``` -------------------------------- ### Set up Connectivity Callbacks Source: https://github.com/rwbutler/connectivity/blob/main/README.md Instantiate Connectivity and assign closures to be invoked on connection or disconnection events. The `updateConnectionStatus` function handles the logic for different connection states. ```swift let connectivity: Connectivity = Connectivity() let connectivityChanged: (Connectivity) -> Void = { [weak self] connectivity in self?.updateConnectionStatus(connectivity.status) } connectivity.whenConnected = connectivityChanged connectivity.whenDisconnected = connectivityChanged func updateConnectionStatus(_ status: Connectivity.ConnectivityStatus) { switch status { case .connected: case .connectedViaWiFi: case .connectedViaWiFiWithoutInternet: case .connectedViaCellular: case .connectedViaCellularWithoutInternet: case .notConnected: } } ``` -------------------------------- ### Initialize Connectivity Publisher with Configuration Source: https://github.com/rwbutler/connectivity/blob/main/CHANGELOG.md A Connectivity publisher can be initialized with a custom configuration object, allowing for specific settings like URLSession configuration. This feature was added in version 5.3.0. ```swift let publisher = Connectivity.Publisher( configuration: .init() .configureURLSession(.default) ) ``` -------------------------------- ### Monitor Connectivity Changes with Callbacks Source: https://context7.com/rwbutler/connectivity/llms.txt Instantiate Connectivity and configure callbacks for connection and disconnection events. Call `startNotifier()` to begin monitoring. Ensure `stopNotifier()` is called when monitoring is no longer needed, typically in `deinit`. ```swift import Connectivity class NetworkManager { private let connectivity = Connectivity() func setupConnectivityMonitoring() { // Configure callbacks for connectivity changes connectivity.whenConnected = { connectivity in print("Connected via: \(connectivity.status)") print("Current interface: \(connectivity.currentInterface)") print("Available interfaces: \(connectivity.availableInterfaces)") } connectivity.whenDisconnected = { connectivity in print("Disconnected: \(connectivity.status)") } // Start monitoring for connectivity changes connectivity.startNotifier() } func stopMonitoring() { connectivity.stopNotifier() } deinit { connectivity.stopNotifier() } } ``` -------------------------------- ### Add OHHTTPStubs/Swift to Podfile (Objective-C) Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md Include this line in your Podfile if you only intend to use OHHTTPStubs from Objective-C. ```ruby pod 'OHHTTPStubs/Swift' ``` -------------------------------- ### Add OHHTTPStubs/Swift to Podfile Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md Use this line in your Podfile if you intend to use OHHTTPStubs from Swift. It includes default subspecs and Swift API wrappers. ```ruby pod 'OHHTTPStubs/Swift' # includes the Default subspec, with support for NSURLSession & JSON, and the Swiftier API wrappers ``` -------------------------------- ### Integrate Connectivity via Carthage Source: https://github.com/rwbutler/connectivity/blob/main/CHANGELOG.md Add this line to your Cartfile to include the Connectivity framework in your project. ```text github "rwbutler/Connectivity" ``` -------------------------------- ### Add OHHTTPStubs to Podfile (Objective-C) Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md Include this line in your Podfile if you only intend to use OHHTTPStubs from Objective-C. ```ruby pod 'OHHTTPStubs' ``` -------------------------------- ### Configure Connectivity URLs and Thresholds Source: https://context7.com/rwbutler/connectivity/llms.txt Customize the connectivity check endpoints, success thresholds, and URLSession configurations. ```swift import Connectivity let connectivity = Connectivity() // Configure custom connectivity check URLs connectivity.connectivityURLs = [ URL(string: "https://www.apple.com/library/test/success.html")!, URL(string: "https://captive.apple.com/hotspot-detect.html")!, URL(string: "https://your-domain.com/health-check")! ] // Set success threshold - 75% means 3 out of 4 URLs must succeed connectivity.successThreshold = Connectivity.Percentage(75.0) // Configure authentication for protected endpoints connectivity.bearerToken = "your-bearer-token" // Or use custom authorization header connectivity.authorizationHeader = "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" // Configure URL session settings Connectivity.urlSessionConfiguration = { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 10.0 config.timeoutIntervalForResource = 10.0 config.requestCachePolicy = .reloadIgnoringCacheData return config }() // Set the framework to use (Network framework recommended for iOS 12+) connectivity.framework = .network // or .systemConfiguration for legacy connectivity.whenConnected = { conn in print("Verified Internet connectivity via \(conn.currentInterface)") } connectivity.startNotifier() ``` -------------------------------- ### Add Connectivity via Swift Package Manager Source: https://github.com/rwbutler/connectivity/blob/main/README.md The repository URL for adding Connectivity as a Swift Package Dependency in Xcode 11 and above. ```plaintext https://github.com/rwbutler/connectivity ``` -------------------------------- ### Use Network Framework Source: https://github.com/rwbutler/connectivity/blob/main/README.md Enable the use of the `Network` framework for connectivity checks on iOS 12 and above by setting the `framework` property to `.network`. The default is `.systemConfiguration`. ```swift let connectivity = Connectivity() connectivity.framework = .network ``` -------------------------------- ### Handle Connectivity Statuses Source: https://context7.com/rwbutler/connectivity/llms.txt This function demonstrates how to react to different `Connectivity.Status` values, including various connected states and offline scenarios. ```swift import Connectivity func handleConnectivityStatus(_ status: Connectivity.Status) { switch status { case .connected: // Generic connection with Internet (interface undetermined) showOnlineUI() case .connectedViaWiFi: // WiFi with verified Internet access showOnlineUI() enableHighBandwidthFeatures() case .connectedViaCellular: // Cellular with verified Internet access showOnlineUI() enableDataSaverMode() case .connectedViaEthernet: // Ethernet with verified Internet access (macOS/tvOS) showOnlineUI() enableHighBandwidthFeatures() case .connectedViaWiFiWithoutInternet: // WiFi connected but no Internet - likely captive portal showCaptivePortalWarning() promptUserToAuthenticate() case .connectedViaCellularWithoutInternet: // Cellular connected but no Internet showOfflineUI() case .connectedViaEthernetWithoutInternet: // Ethernet connected but no Internet showOfflineUI() case .notConnected: // No network interface available showOfflineUI() enableOfflineMode() case .determining: // Initial state while checking connectivity showLoadingIndicator() } } ``` -------------------------------- ### Instantiate Connectivity with HTTP Support Source: https://github.com/rwbutler/connectivity/blob/main/README.md Instantiate the Connectivity object to support HTTP URLs in addition to HTTPS. This requires the `NSAllowsArbitraryLoads` flag to be set in your app's Info.plist. ```swift let connectivity = Connectivity(shouldUseHTTPS: false) ``` -------------------------------- ### Add OHHTTPStubs to Cartfile Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md Add this line to your Cartfile to integrate OHHTTPStubs using Carthage. The Carthage build includes all features. ```plaintext github "AliSoftware/OHHTTPStubs" ``` -------------------------------- ### Configure Connectivity with Fluent Interface Source: https://github.com/rwbutler/connectivity/blob/main/README.md Use the new fluent interface introduced in Connectivity 5.2.0 to configure polling and response validation by passing a `ConnectivityConfiguration` object to the initializer. ```swift let connectivity = Connectivity( configuration: .init() .configurePolling(interval: 5) .configureResponseValidation(.containsExpectedResponseString, expected: "Success") ) ``` -------------------------------- ### Configure Connectivity with URLs Source: https://github.com/rwbutler/connectivity/blob/main/CHANGELOG.md URL objects can still be used for connectivity checks when configuring the framework via the fluent API. This is an alternative to using URLRequest objects. ```swift ConnectivityConfiguration() .configureConnectivity(urls: [ URL(...) ]) ``` -------------------------------- ### Combine Publisher for Connectivity Changes Source: https://context7.com/rwbutler/connectivity/llms.txt Utilize `Connectivity.Publisher` to receive updates on connectivity status changes using Combine. This requires iOS 13+, macOS 10.15+, or tvOS 13.0+. ```swift import Combine import Connectivity @available(iOS 13.0, *) class ConnectivityViewModel: ObservableObject { @Published var isConnected: Bool = false @Published var connectionType: String = "Unknown" private var cancellable: AnyCancellable? init() { startMonitoring() } func startMonitoring() { let configuration = ConnectivityConfiguration() .configurePolling(isEnabled: true, interval: 10.0, offlineOnly: true) .configureURLSession(.default) let publisher = Connectivity.Publisher(configuration: configuration) cancellable = publisher .receive(on: DispatchQueue.main) .sink { [weak self] connectivity in self?.isConnected = connectivity.isConnected self?.connectionType = connectivity.status.description // Access detailed interface information print("Current interface: \(connectivity.currentInterface)") print("Available interfaces: \(connectivity.availableInterfaces)") } } func stopMonitoring() { cancellable?.cancel() cancellable = nil } deinit { stopMonitoring() } } ``` -------------------------------- ### Perform One-Off Connectivity Check Source: https://github.com/rwbutler/connectivity/blob/main/README.md Instantiate `Connectivity` and use `checkConnectivity` to perform a single check of the network status. The callback provides the current connectivity status. ```swift let connectivity = Connectivity() connectivity.checkConnectivity { connectivity in switch connectivity.status { case .connected: break case .connectedViaWiFi: break case .connectedViaWiFiWithoutInternet: break case .connectedViaCellular: break case .connectedViaCellularWithoutInternet: break case .notConnected: break } } ``` -------------------------------- ### Configure Connectivity with URLRequests Source: https://github.com/rwbutler/connectivity/blob/main/CHANGELOG.md Use URLRequest objects for connectivity checks when configuring the framework via the fluent API. This was introduced in version 6.1.0. ```swift ConnectivityConfiguration() .configureConnectivity(urlRequests: [ URLRequest(...) ]) ``` -------------------------------- ### Enable/Disable OHHTTPStubs Globally Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md Control the global enablement of OHHTTPStubs. Use this to turn stubbing on or off as needed during development or testing. ```Objective-C [HTTPStubs setEnabled:] ``` -------------------------------- ### Observe Connectivity Changes with NotificationCenter Source: https://context7.com/rwbutler/connectivity/llms.txt Register for .ConnectivityDidChange notifications to handle network status updates without using callbacks or Combine. ```swift import Connectivity class NetworkObserver { private let connectivity = Connectivity() init() { // Register for connectivity change notifications NotificationCenter.default.addObserver( self, selector: #selector(connectivityDidChange(_:)), name: .ConnectivityDidChange, object: nil ) // Start the notifier to begin receiving notifications connectivity.startNotifier() } @objc private func connectivityDidChange(_ notification: Notification) { guard let connectivity = notification.object as? Connectivity else { return } print("Connectivity changed: \(connectivity.status)") print("Is connected: \(connectivity.isConnected)") print("Interface: \(connectivity.currentInterface)") // Update UI or trigger actions based on connectivity DispatchQueue.main.async { if connectivity.isConnected { self.syncPendingData() } } } private func syncPendingData() { // Sync data when Internet becomes available } deinit { NotificationCenter.default.removeObserver(self) connectivity.stopNotifier() } } ``` -------------------------------- ### Check Specific Connection Types Source: https://github.com/rwbutler/connectivity/blob/main/README.md Directly query boolean properties on the `Connectivity` object to determine specific types of network connections. ```swift var isConnectedViaCellular: Bool var isConnectedViaWiFi: Bool var isConnectedViaCellularWithoutInternet: Bool var isConnectedViaWiFiWithoutInternet: Bool ``` -------------------------------- ### Enable/Disable OHHTTPStubs for Specific Sessions Source: https://github.com/rwbutler/connectivity/blob/main/Example/Pods/OHHTTPStubs/README.md Manage OHHTTPStubs enablement on a per-`NSURLSession` basis. This allows for more granular control over stubbing behavior. ```Objective-C [HTTPStubs setEnabled:forSessionConfiguration:] ``` -------------------------------- ### Implement Custom Response Validation Source: https://context7.com/rwbutler/connectivity/llms.txt Create custom validators by implementing the ConnectivityResponseValidator protocol or use built-in validation modes. ```swift import Connectivity // Custom validator for a specific API response format class CustomAPIValidator: ConnectivityResponseValidator { func isResponseValid(urlRequest: URLRequest, response: URLResponse?, data: Data?) -> Bool { guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let data = data else { return false } // Parse JSON response from your connectivity endpoint do { if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let status = json["status"] as? String { return status == "online" } } catch { return false } return false } } // Using built-in validators let connectivity = Connectivity() // Validate response contains expected string connectivity.validationMode = .containsExpectedResponseString connectivity.expectedResponseString = "Success" // Validate response equals expected string exactly connectivity.validationMode = .equalsExpectedResponseString connectivity.expectedResponseString = "OK" // Validate response matches regex pattern connectivity.validationMode = .matchesRegularExpression connectivity.expectedResponseRegEx = ".*?
.*?Success.*?.*" // Use custom validator connectivity.validationMode = .custom connectivity.responseValidator = CustomAPIValidator() connectivity.startNotifier() ``` -------------------------------- ### Captive Portal Success HTML Source: https://github.com/rwbutler/connectivity/blob/main/README.md The standard HTML response expected by iOS to verify that a network connection is not being intercepted by a captive portal. ```html