From 5156c25bbb3c05dedad2dd498d5de2f6cf70fedf Mon Sep 17 00:00:00 2001
From: brennanMKE <277419+brennanMKE@users.noreply.github.com>
Date: Fri, 26 Nov 2021 18:14:06 -0800
Subject: [PATCH] init
---
.gitignore | 2 +
.../contents.xcworkspacedata | 7 +
.../xcshareddata/IDEWorkspaceChecks.plist | 8 +
Package.swift | 35 +++
README.md | 38 +++
.../ConnectivityKit/ConnectivityMonitor.swift | 96 +++++++
Sources/ConnectivityKit/NetworkMonitor.swift | 94 +++++++
.../ConnectivityKit/ReachabilityMonitor.swift | 67 +++++
Sources/Reachability/Reachability.h | 88 +++++++
Sources/Reachability/Reachability.m | 249 ++++++++++++++++++
.../ConnectivityKitTests.swift | 5 +
11 files changed, 689 insertions(+)
create mode 100644 .gitignore
create mode 100644 ConnectivityKit.xcworkspace/contents.xcworkspacedata
create mode 100644 ConnectivityKit.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
create mode 100644 Package.swift
create mode 100644 README.md
create mode 100644 Sources/ConnectivityKit/ConnectivityMonitor.swift
create mode 100644 Sources/ConnectivityKit/NetworkMonitor.swift
create mode 100644 Sources/ConnectivityKit/ReachabilityMonitor.swift
create mode 100644 Sources/Reachability/Reachability.h
create mode 100644 Sources/Reachability/Reachability.m
create mode 100644 Tests/ConnectivityKitTests/ConnectivityKitTests.swift
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..47042c2
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+.DS_Store
+xcuserdata
diff --git a/ConnectivityKit.xcworkspace/contents.xcworkspacedata b/ConnectivityKit.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 0000000..ca3329e
--- /dev/null
+++ b/ConnectivityKit.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/ConnectivityKit.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ConnectivityKit.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 0000000..18d9810
--- /dev/null
+++ b/ConnectivityKit.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+
+
+
+
+ IDEDidComputeMac32BitWarning
+
+
+
diff --git a/Package.swift b/Package.swift
new file mode 100644
index 0000000..76189ff
--- /dev/null
+++ b/Package.swift
@@ -0,0 +1,35 @@
+// swift-tools-version:5.5
+// The swift-tools-version declares the minimum version of Swift required to build this package.
+
+import PackageDescription
+
+let package = Package(
+ name: "ConnectivityKit",
+ platforms: [
+ .iOS(.v10),
+ .macOS(.v10_14),
+ .tvOS(.v12),
+ .watchOS(.v6)
+ ],
+ products: [
+ .library(
+ name: "ConnectivityKit",
+ targets: ["ConnectivityKit"]),
+ ],
+ dependencies: [],
+ targets: [
+ .target(
+ name: "ConnectivityKit",
+ dependencies: ["Reachability"],
+ path: "Sources/ConnectivityKit"),
+ .target(
+ name: "Reachability",
+ dependencies: [],
+ path: "Sources/Reachability",
+ publicHeadersPath: ""
+ ),
+ .testTarget(
+ name: "ConnectivityKitTests",
+ dependencies: ["ConnectivityKit"]),
+ ]
+)
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..5ca39f4
--- /dev/null
+++ b/README.md
@@ -0,0 +1,38 @@
+# ConnectivityKit
+
+Adapting to changes in network connectivity can allow for suspending or resuming network activity. When entering an elevator or going through a tunnel our devices typically lose connectivity completely. We also move out of range of WiFi and transition to a cellular connection. Apple's [Network Framework] includes [NWPathMonitor] which provides updates in response to changes to [NWPath]. This framework was introduced in 2018 and is a modern replacement to [SCNetworkReachability], simply known as the Reachability API which does not support many of the features supported by modern network protocols such as WiFi 6 and 5G.
+
+For apps which still support older OS versions it is necessary to use Reachability while most users are able to use the Network framework. This package automatically users the API which is available based on the OS version.
+
+See: [Introduction to Network.framework]
+
+## Usage
+
+This package includes `ConnectivityMonitor` which internally uses `NetworkMonitor` or `ReachabilityMonitor` which are simply available as `AnyConnectivityMonitor`. For recent OS versions of iOS, macOS, tvOS and watchOS the `NetworkMonitor` will be used. For earlier versions `ReachabilityMonitor` will be used.
+
+Simply call the `start` function and provide a path handler to get updates. Call the `cancel` function to discontinue monitoring.
+
+## Swift Package
+
+This project is set up as a Swift Package which can be used by the [Swift Package Manager] (SPM) with Xcode. In your `Package.swift` add this package with the code below.
+
+```swift
+dependencies: [
+ .package(url: "https://github.com/brennanMKE/ConnectivityKit", from: "1.0.0"),
+],
+```
+
+## Supporting iOS 10.0 and Later
+
+Since this package automatically handles the selection of the implementation your code can just use `ConnectivityMonitor` to get updates to the network path. The Reachability API comes from the [System Configuration Framework] which is available for all of Apple's platforms except watchOS. The implementation for the `ReachabilityMonitor` will get an empty implementation for watchOS prior to watchOS 6.0 which is when [Network Framework] was first made available to watchOS.
+
+If your Deployment Target for any of Apple's platforms supports [Network Framework] then it will always use the modern implementation. This package will allow you to use the same code across all platforms and respond to changes to network connectivity.
+
+---
+[Network Framework]: https://developer.apple.com/documentation/network
+[NWPathMonitor]: https://developer.apple.com/documentation/network/nwpathmonitor
+[NWPath]: https://developer.apple.com/documentation/network/nwpath
+[SCNetworkReachability]: https://developer.apple.com/documentation/systemconfiguration/scnetworkreachability-g7d
+[System Configuration Framework]: https://developer.apple.com/documentation/systemconfiguration
+[Introduction to Network.framework]: https://developer.apple.com/videos/play/wwdc2018/715
+[Swift Package Manager]: https://swift.org/package-manager/
diff --git a/Sources/ConnectivityKit/ConnectivityMonitor.swift b/Sources/ConnectivityKit/ConnectivityMonitor.swift
new file mode 100644
index 0000000..4254c12
--- /dev/null
+++ b/Sources/ConnectivityKit/ConnectivityMonitor.swift
@@ -0,0 +1,96 @@
+import Foundation
+
+public enum ConnectivityStatus: String {
+ case satisfied
+ case unsatisfied
+ case requiresConnection
+}
+
+extension ConnectivityStatus: CustomStringConvertible {
+ public var description: String {
+ rawValue
+ }
+}
+
+public enum ConnectivityInterfaceType: String {
+ case other
+ case wifi
+ case cellular
+ case wiredEthernet
+ case loopback
+}
+
+public struct ConnectivityInterface {
+ public let name: String
+ public let type: ConnectivityInterfaceType
+}
+
+extension ConnectivityInterface: CustomStringConvertible {
+ public var description: String {
+ "\(name) (\(type))"
+ }
+}
+
+extension Array where Element == ConnectivityInterface {
+ public var description: String {
+ self.map { "\($0.name) (\($0.type))" }.joined(separator: ", ")
+ }
+}
+
+public struct ConnectivityPath {
+ public let status: ConnectivityStatus
+ public let availableInterfaces: [ConnectivityInterface]
+ public let isExpensive: Bool
+ public let supportsDNS: Bool
+ public let supportsIPv4: Bool
+ public let supportsIPv6: Bool
+}
+
+extension ConnectivityPath: CustomStringConvertible {
+ public var description: String {
+ [
+ "\(status): \(availableInterfaces.description)",
+ "Expensive = \(isExpensive ? "YES" : "NO")",
+ "DNS = \(supportsDNS ? "YES" : "NO")",
+ "IPv4 = \(supportsIPv4 ? "YES" : "NO")",
+ "IPv6 = \(supportsIPv6 ? "YES" : "NO")"
+ ].joined(separator: "; ")
+ }
+}
+
+public typealias PathUpdateHandler = (ConnectivityPath) -> Void
+
+public protocol AnyConnectivityMonitor {
+ func start(pathUpdateQueue: DispatchQueue, pathUpdateHandler: @escaping PathUpdateHandler)
+ func cancel()
+}
+
+public class ConnectivityMonitor {
+ private var monitor: AnyConnectivityMonitor?
+ private let queue = DispatchQueue(label: "com.acme.connectivity", qos: .background)
+
+ public init() {}
+
+ public func start(pathUpdateQueue: DispatchQueue, pathUpdateHandler: @escaping PathUpdateHandler) {
+ let monitor = createMonitor()
+ monitor.start(pathUpdateQueue: pathUpdateQueue, pathUpdateHandler: pathUpdateHandler)
+ self.monitor = monitor
+ }
+
+ public func cancel() {
+ guard let monitor = monitor else { return }
+ monitor.cancel()
+ self.monitor = nil
+ }
+
+ private func createMonitor() -> AnyConnectivityMonitor {
+ let result: AnyConnectivityMonitor
+ if #available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *) {
+ result = NetworkMonitor()
+ } else {
+ result = ReachabilityMonitor()
+ }
+ return result
+ }
+
+}
diff --git a/Sources/ConnectivityKit/NetworkMonitor.swift b/Sources/ConnectivityKit/NetworkMonitor.swift
new file mode 100644
index 0000000..cebe609
--- /dev/null
+++ b/Sources/ConnectivityKit/NetworkMonitor.swift
@@ -0,0 +1,94 @@
+import Foundation
+import Network
+
+@available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+extension ConnectivityStatus {
+ init(status: NWPath.Status) {
+ switch status {
+ case .satisfied:
+ self = .satisfied
+ case .unsatisfied:
+ self = .unsatisfied
+ case .requiresConnection:
+ self = .requiresConnection
+ @unknown default:
+ self = .unsatisfied
+ }
+ }
+}
+
+@available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+extension ConnectivityInterfaceType {
+ init(interfaceType: NWInterface.InterfaceType) {
+ switch interfaceType {
+ case .other:
+ self = .other
+ case .wifi:
+ self = .wifi
+ case .cellular:
+ self = .cellular
+ case .wiredEthernet:
+ self = .wiredEthernet
+ case .loopback:
+ self = .loopback
+ @unknown default:
+ self = .other
+ }
+ }
+}
+
+@available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+extension ConnectivityInterface {
+ init(interface: NWInterface) {
+ name = interface.name
+ type = ConnectivityInterfaceType(interfaceType: interface.type)
+ }
+}
+
+@available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+extension ConnectivityPath {
+ init(path: NWPath) {
+ status = ConnectivityStatus(status: path.status)
+ availableInterfaces = path.availableInterfaces.map { ConnectivityInterface(interface: $0) }
+ isExpensive = path.isExpensive
+ supportsDNS = path.supportsDNS
+ supportsIPv4 = path.supportsIPv4
+ supportsIPv6 = path.supportsIPv6
+ }
+}
+
+@available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+class NetworkMonitor: AnyConnectivityMonitor {
+ private var monitor: NWPathMonitor?
+ private var pathUpdateQueue: DispatchQueue?
+ private var pathUpdateHandler: PathUpdateHandler?
+
+ private let queue = DispatchQueue(label: "com.acme.connectivity.network-monitor", qos: .background)
+
+ @available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+ func start(pathUpdateQueue: DispatchQueue, pathUpdateHandler: @escaping PathUpdateHandler) {
+ self.pathUpdateQueue = pathUpdateQueue
+ self.pathUpdateHandler = pathUpdateHandler
+ // A new instance is required each time a monitor is started
+ let monitor = NWPathMonitor()
+ monitor.pathUpdateHandler = didUpdate(path:)
+ monitor.start(queue: queue)
+ self.monitor = monitor
+ }
+
+ @available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+ func cancel() {
+ guard let monitor = monitor else { return }
+ monitor.cancel()
+ }
+
+ @available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.0, *)
+ func didUpdate(path: NWPath) {
+ guard let pathUpdateHandler = pathUpdateHandler,
+ let pathUpdateQueue = pathUpdateQueue else { return }
+ let connectivityPath = ConnectivityPath(path: path)
+ pathUpdateQueue.async {
+ pathUpdateHandler(connectivityPath)
+ }
+ }
+}
diff --git a/Sources/ConnectivityKit/ReachabilityMonitor.swift b/Sources/ConnectivityKit/ReachabilityMonitor.swift
new file mode 100644
index 0000000..fdac718
--- /dev/null
+++ b/Sources/ConnectivityKit/ReachabilityMonitor.swift
@@ -0,0 +1,67 @@
+import Foundation
+import Reachability
+
+extension ConnectivityStatus {
+
+ init(networkStatus: NetworkStatus) {
+ switch networkStatus {
+ case .notReachable:
+ self = .unsatisfied
+ case .reachableViaWiFi, .reachableViaWWAN:
+ self = .satisfied
+ @unknown default:
+ self = .unsatisfied
+ }
+ }
+}
+
+extension ConnectivityPath {
+
+ init(networkStatus: NetworkStatus, connectionRequired: Bool) {
+ status = ConnectivityStatus(networkStatus: networkStatus)
+ availableInterfaces = []
+ isExpensive = networkStatus == .reachableViaWWAN
+ supportsDNS = false
+ supportsIPv4 = false
+ supportsIPv6 = false
+ }
+}
+
+public class ReachabilityMonitor: AnyConnectivityMonitor {
+ var reachability: Reachability?
+ private var pathUpdateQueue: DispatchQueue?
+ private var pathUpdateHandler: PathUpdateHandler?
+
+ var hostname: String {
+ let result = Bundle.main.infoDictionary?["ReachabilityHostname"] as? String ?? "github.com"
+ return result
+ }
+
+ public func start(pathUpdateQueue: DispatchQueue, pathUpdateHandler: @escaping PathUpdateHandler) {
+ debugPrint(#function)
+ self.pathUpdateQueue = pathUpdateQueue
+ self.pathUpdateHandler = pathUpdateHandler
+ let reachability = Reachability(hostname: hostname)
+ reachability.didChangeHandler = didChange(reachability:)
+ reachability.start()
+ self.reachability = reachability
+ }
+
+ public func cancel() {
+ debugPrint(#function)
+ guard let reachability = reachability else { return }
+ reachability.cancel()
+ self.reachability = nil
+ }
+
+ func didChange(reachability: Reachability) {
+ debugPrint(#function)
+ guard let pathUpdateHandler = pathUpdateHandler,
+ let pathUpdateQueue = pathUpdateQueue else { return }
+ let connectivityPath = ConnectivityPath(networkStatus: reachability.currentStatus, connectionRequired: reachability.connectionRequired)
+ debugPrint("\(connectivityPath)")
+ pathUpdateQueue.async {
+ pathUpdateHandler(connectivityPath)
+ }
+ }
+}
diff --git a/Sources/Reachability/Reachability.h b/Sources/Reachability/Reachability.h
new file mode 100644
index 0000000..b81219c
--- /dev/null
+++ b/Sources/Reachability/Reachability.h
@@ -0,0 +1,88 @@
+/*
+
+ File: Reachability.h
+ Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.
+
+ This file lifted from: https://gist.github.com/darkseed/1182373
+
+ Version: 2.2 - ARCified
+
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
+ ("Apple") in consideration of your agreement to the following terms, and your
+ use, installation, modification or redistribution of this Apple software
+ constitutes acceptance of these terms. If you do not agree with these terms,
+ please do not use, install, modify or redistribute this Apple software.
+
+ In consideration of your agreement to abide by the following terms, and subject
+ to these terms, Apple grants you a personal, non-exclusive license, under
+ Apple's copyrights in this original Apple software (the "Apple Software"), to
+ use, reproduce, modify and redistribute the Apple Software, with or without
+ modifications, in source and/or binary forms; provided that if you redistribute
+ the Apple Software in its entirety and without modifications, you must retain
+ this notice and the following text and disclaimers in all such redistributions
+ of the Apple Software.
+ Neither the name, trademarks, service marks or logos of Apple Inc. may be used
+ to endorse or promote products derived from the Apple Software without specific
+ prior written permission from Apple. Except as expressly stated in this notice,
+ no other rights or licenses, express or implied, are granted by Apple herein,
+ including but not limited to any patent rights that may be infringed by your
+ derivative works or by other works in which the Apple Software may be
+ incorporated.
+
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
+ WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
+ WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
+ COMBINATION WITH YOUR PRODUCTS.
+
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
+ DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
+ CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
+ APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ Copyright (C) 2010 Apple Inc. All Rights Reserved.
+
+ */
+
+#import
+
+NS_ASSUME_NONNULL_BEGIN
+
+struct sockaddr;
+
+typedef NS_ENUM(NSInteger, NetworkStatus) {
+ // Apple NetworkStatus Compatible Names.
+ NetworkStatusNotReachable = 0,
+ NetworkStatusReachableViaWWAN = 1,
+ NetworkStatusReachableViaWiFi = 2
+};
+
+@class Reachability;
+
+typedef void(^ReachabilityDidChangeHandler)(Reachability * reachability);
+
+@interface Reachability: NSObject
+
+@property (nonatomic, nullable) ReachabilityDidChangeHandler didChangeHandler;
+
+@property (readonly) NetworkStatus currentStatus;
+
+/// WWAN may be available, but not active until a connection has been established.
+/// WiFi may require a connection for VPN on Demand.
+@property (readonly) BOOL connectionRequired;
+
+/// reachabilityWithHostname- Use to check the reachability of a particular host name.
++ (Reachability*)reachabilityWithHostname:(NSString *)hostname;
+
+/// Start listening for reachability notifications on the current run loop
+- (BOOL)start;
+
+/// Cancel listening for reachability notifications on the current run loop
+- (void)cancel;
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/Sources/Reachability/Reachability.m b/Sources/Reachability/Reachability.m
new file mode 100644
index 0000000..6c6f799
--- /dev/null
+++ b/Sources/Reachability/Reachability.m
@@ -0,0 +1,249 @@
+/*
+
+ File: Reachability.m
+ Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.
+
+ This file lifted from: https://gist.github.com/darkseed/1182373
+
+ Version: 2.2 - ARCified
+
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
+ ("Apple") in consideration of your agreement to the following terms, and your
+ use, installation, modification or redistribution of this Apple software
+ constitutes acceptance of these terms. If you do not agree with these terms,
+ please do not use, install, modify or redistribute this Apple software.
+
+ In consideration of your agreement to abide by the following terms, and subject
+ to these terms, Apple grants you a personal, non-exclusive license, under
+ Apple's copyrights in this original Apple software (the "Apple Software"), to
+ use, reproduce, modify and redistribute the Apple Software, with or without
+ modifications, in source and/or binary forms; provided that if you redistribute
+ the Apple Software in its entirety and without modifications, you must retain
+ this notice and the following text and disclaimers in all such redistributions
+ of the Apple Software.
+ Neither the name, trademarks, service marks or logos of Apple Inc. may be used
+ to endorse or promote products derived from the Apple Software without specific
+ prior written permission from Apple. Except as expressly stated in this notice,
+ no other rights or licenses, express or implied, are granted by Apple herein,
+ including but not limited to any patent rights that may be infringed by your
+ derivative works or by other works in which the Apple Software may be
+ incorporated.
+
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
+ WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
+ WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
+ COMBINATION WITH YOUR PRODUCTS.
+
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
+ DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
+ CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
+ APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ Copyright (C) 2010 Apple Inc. All Rights Reserved.
+
+ */
+
+#import "TargetConditionals.h"
+
+#import "Reachability.h"
+
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_OSX
+
+#import
+#import
+#import
+#import
+#import
+#import
+
+#import
+#import
+
+static void printReachabilityFlags(SCNetworkReachabilityFlags flags, const char *comment) {
+ #if kShouldPrintReachabilityFlags
+ NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
+ #if TARGET_OS_IPHONE
+ (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
+ #else
+ '-',
+ #endif
+ (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
+ (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
+ (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
+ (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
+ (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
+ (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
+ (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
+ (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
+ comment
+ );
+ #endif
+}
+
+static void reachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) {
+#pragma unused (target, flags)
+ NSCAssert(info != NULL, @"info was NULL in reachabilityCallback");
+ NSCAssert([(__bridge NSObject *) info isKindOfClass:[Reachability class]], @"info was wrong class in reachabilityCallback");
+
+ NSLog(@"Callback");
+
+ // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
+ // in case someone uses the Reachablity object in a different thread.
+ @autoreleasepool {
+ Reachability *reachability = (__bridge Reachability *)info;
+ // Post a notification to notify the client that the network reachability changed.
+ if (reachability.didChangeHandler != nil) {
+ reachability.didChangeHandler(reachability);
+ }
+ }
+}
+
+@implementation Reachability {
+ SCNetworkReachabilityRef _reachabilityRef;
+}
+
+- (BOOL)start {
+ BOOL retVal = NO;
+ SCNetworkReachabilityContext context = {0, (__bridge void *)self, NULL, NULL, NULL};
+
+ if (SCNetworkReachabilitySetCallback(_reachabilityRef, reachabilityCallback, &context) &&
+ SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetMain(), kCFRunLoopDefaultMode)) {
+ retVal = YES;
+ }
+
+ return retVal;
+}
+
+- (void)cancel {
+ if (_reachabilityRef != NULL) {
+ SCNetworkReachabilityUnscheduleFromRunLoop(_reachabilityRef, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
+ }
+}
+
+- (void)dealloc {
+ [self cancel];
+
+ if (_reachabilityRef != NULL) {
+ CFRelease(_reachabilityRef);
+ }
+}
+
++ (Reachability *)reachabilityWithHostname:(NSString *)hostname {
+ Reachability *retVal = NULL;
+ SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostname UTF8String]);
+
+ if (reachability != NULL) {
+ retVal = [[self alloc] init];
+
+ if (retVal != NULL) {
+ retVal->_reachabilityRef = reachability;
+ }
+ else {
+ CFRelease(reachability);
+ }
+ }
+
+ return retVal;
+}
+
+#pragma mark Network Flag Handling
+
+- (NetworkStatus)localWiFiStatusForFlags:(SCNetworkReachabilityFlags)flags {
+ printReachabilityFlags(flags, "localWiFiStatusForFlags");
+
+ BOOL retVal = NetworkStatusNotReachable;
+
+ if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)) {
+ retVal = NetworkStatusReachableViaWiFi;
+ }
+
+ return retVal;
+}
+
+- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags {
+ printReachabilityFlags(flags, "networkStatusForFlags");
+
+ if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) {
+ // if target host is not reachable
+ return NetworkStatusNotReachable;
+ }
+
+ NetworkStatus retVal = NetworkStatusNotReachable;
+
+ if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) {
+ // if target host is reachable and no connection is required
+ // then we'll assume (for now) that your on Wi-Fi
+ retVal = NetworkStatusReachableViaWiFi;
+ }
+
+
+ if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
+ (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)) {
+ // ... and the connection is on-demand (or on-traffic) if the
+ // calling application is using the CFSocketStream or higher APIs
+
+ if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) {
+ // ... and no [user] intervention is needed
+ retVal = NetworkStatusReachableViaWiFi;
+ }
+ }
+
+ #if TARGET_OS_IPHONE
+ if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
+ // ... but WWAN connections are OK if the calling application
+ // is using the CFNetwork (CFSocketStream?) APIs.
+ retVal = NetworkStatusReachableViaWWAN;
+ }
+ #endif
+
+ return retVal;
+}
+
+- (NetworkStatus)currentStatus {
+ NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");
+
+ NetworkStatus retVal = NetworkStatusNotReachable;
+ SCNetworkReachabilityFlags flags;
+
+ if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags)) {
+ retVal = [self networkStatusForFlags:flags];
+ }
+
+ return retVal;
+}
+
+- (BOOL)connectionRequired {
+ NSAssert(_reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef");
+
+ SCNetworkReachabilityFlags flags;
+
+ if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags)) {
+ return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
+ }
+
+ return NO;
+}
+
+@end
+
+#else
+
+@implementation Reachability
+
++ (Reachability*)reachabilityWithHostname:(NSString *)hostname {
+ return NULL;
+}
+
+- (BOOL)start {
+ return NO;
+}
+
+- (void)cancel {}
+
+@end
+
+#endif
diff --git a/Tests/ConnectivityKitTests/ConnectivityKitTests.swift b/Tests/ConnectivityKitTests/ConnectivityKitTests.swift
new file mode 100644
index 0000000..9c737ff
--- /dev/null
+++ b/Tests/ConnectivityKitTests/ConnectivityKitTests.swift
@@ -0,0 +1,5 @@
+import XCTest
+@testable import ConnectivityKit
+
+final class ConnectivityKitTests: XCTestCase {
+}