XUtils

Connectivity

🌐 Makes Internet connectivity detection more robust by detecting Wi-Fi networks without Internet access.


What’s new in Connectivity 7.0.0?

For more information, see CHANGELOG.md.

Cocoapods

CocoaPods is a dependency manager which integrates dependencies into your Xcode workspace. To install it using Ruby gems run:

gem install cocoapods

To install Connectivity using Cocoapods, simply add the following line to your Podfile:

pod "Connectivity"

Then run the command:

pod install

For more information see here.

Carthage

Carthage is a dependency manager which produces a binary for manual integration into your project. It can be installed via Homebrew using the commands:

brew update
brew install carthage

In order to integrate Connectivity into your project via Carthage, add the following line to your project’s Cartfile:

github "rwbutler/Connectivity"

From the macOS Terminal run carthage update --platform iOS to build the framework then drag Connectivity.framework into your Xcode project.

For more information see here.

Callbacks

To get started using Connectivity, simply instantiate an instance and assign a closure to be invoked when Connectivity detects that you are connected to the Internet, when disconnected, or in both cases as follows:

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:
    }
        
}

Then to start listening for changes in Connectivity call:

connectivity.startNotifier()

Then remember to call connectivity.stopNotifier() when you are done.

Configuration

The framework can be configured by setting the relevant properties on the Connectivity object directly e.g.

let connectivity = Connectivity()
connectivity.pollingInterval = 5
connectivity.expectedResponseString = "Success"
connectivity.validationMode = .containsExpectedResponseString

Connectivity 5.2.0 introduces a new fluent interface for configuring the framework by passing a ConnectivityConfiguration object to the Connectivity initializer.

let connectivity = Connectivity(
    configuration: .init()
                .configurePolling(interval: 5)
                .configureResponseValidation(.containsExpectedResponseString, expected: "Success")
)

One-Off Checks

Sometimes you only want to check the connectivity state as a one-off. To do so, instantiate a Connectivity object then check the status property as follows:

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
	}

}

Alternatively, you may check the following properties of the Connectivity object directly if you are only interested in certain types of connections:

var isConnectedViaCellular: Bool

var isConnectedViaWiFi: Bool
    
var isConnectedViaCellularWithoutInternet: Bool

var isConnectedViaWiFiWithoutInternet: Bool

Network Framework

From version 2.0.0, Connectivity provides the option of using the new Network framework where a device is running iOS 12 or above. To make use of this functionality set the framework property to .network (the default value is .systemConfiguration) as follows:

let connectivity = Connectivity()
connectivity.framework = .network

Below iOS 12, Connectivity will default to the traditional behaviour of using Reachability (SystemConfiguration.framework) to determine the availability of network interfaces.

For more information, refer to CHANGELOG.md.

Notifications

If you prefer using notifications to observe changes in connectivity, you may add an observer on the default NotificationCenter:

NotificationCenter.default.addObserver(_:selector:name:object:)

Listening for Notification.Name.ConnectivityDidChange, the object property of received notifications will contain the Connectivity object which you can use to query connectivity status.

Polling

In certain cases you may need to be kept constantly apprised of changes in connectivity state and therefore may wish to enable polling. Where enabled, Connectivity will not wait on changes in Reachability state but will poll the connectivity URLs every 10 seconds (this value is configurable by setting the value of the pollingInterval property). ConnectivityDidChange notifications and the closures assigned to the whenConnected and whenDisconnected properties will be invoked only where changes in connectivity state occur.

To enable polling:

connectivity.isPollingEnabled = true
connectivity.startNotifier()

As always, remember to call stopNotifier() when you are done.

SSL

As of Connectivity 1.1.0, using HTTPS for connectivity URLs is the default setting. If your app doesn’t make use of App Transport Security and you wish to make use of HTTP URLs as well as HTTPS ones then either set isHTTPSOnly to false or set shouldUseHTTPS to false when instantiating the Connectivity object as follows*:

let connectivity = Connectivity(shouldUseHTTPS: false)

*Note that the property will not be set if you have not set the NSAllowsArbitraryLoads flag in your app’s Info.plist first.

Threshold

To set the number of successful connections required in order to be deemed successfully connected, set the successThreshold property. The value is specified as a percentage indicating the percentage of successful connections i.e. if four connectivity URLs are set in the connectivityURLs property and a threshold of 75% is specified then three out of the four checks must succeed in order for our app to be deemed connected:

connectivity.successThreshold = Connectivity.Percentage(75.0)

Response Validation

There are three different validation modes available for checking response content these being:

  • .containsExpectedResponseString - Checks that the response contains the expected response as defined by the expectedResponseString property.
  • .equalsExpectedResponseString - Checks that the response equals the expected response as defined by the expectedResponseString property.
  • .matchesRegularExpression - Checks that the response matches the regular expression as defined by the expectedResponseRegEx property.
  • .custom - Allows a custom response validator to be set. If this validation mode is specified, then an implementation of ConnectivityResponseValidator protocol must be supplied as the value of the responseValidator property on the Connectivity object.

Supplied validators include:

  • ConnectivityResponseStringEqualityValidator: Determines whether the response string is equal to an expected string.
  • ConnectivityResponseContainsStringValidator: Determines whether the response string contains an expected string.
  • ConnectivityResponseRegExValidator: Determines whether the response string matches a given regular expression.

Known Issues

Caller responsible for retaining the Connectivity object

Please ensure that any implementation making use of this framework holds a strong reference to the Connectivity object for the duration of its use (as an instance variable or otherwise). If the object is deallocated before the callback is invoked, the result will be non-deterministic.

Simulator issues

Before reporting a bug please ensure that you have tested on a physical device as on simulator changes in network adapter state are not reported correctly by iOS frameworks particularly when transitioning from a disconnected -> connected state. This behaviour functions correctly on a physical device. Setting pollWhileOfflineOnly = true should resolve this issue.

Author

Ross Butler

Additional Software

Controls

AnimatedGradientView
AnimatedGradientView

Tools

  • Clear DerivedData - Utility to quickly clear your DerivedData directory simply by typing cdd from the Terminal.
  • Config Validator - Config Validator validates & uploads your configuration files and cache clears your CDN as part of your CI process.
  • IPA Uploader - Uploads your apps to TestFlight & App Store.
  • Palette - Makes your TypographyKit color palette available in Xcode Interface Builder.
Config Validator IPA Uploader Palette
Config Validator IPA Uploader Palette

Articles

  • coming soon...