Last active
January 10, 2017 17:41
-
-
Save fongd/0ae8be76e945102e3741e1b4804795da to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Reachability.swift | |
// | |
import SystemConfiguration | |
public enum ReachabilityType: CustomStringConvertible { | |
case WWAN | |
case WiFi | |
public var description: String { | |
switch self { | |
case .WWAN: return "WWAN" | |
case .WiFi: return "WiFi" | |
} | |
} | |
} | |
public enum ReachabilityStatus: CustomStringConvertible { | |
case Offline | |
case Online(ReachabilityType) | |
case Unknown | |
public var description: String { | |
switch self { | |
case .Offline: return "Offline" | |
case .Online(let type): return "Online (\(type))" | |
case .Unknown: return "Unknown" | |
} | |
} | |
} | |
open class Reachability { | |
class func connectionStatus() -> ReachabilityStatus { | |
var zeroAddress = sockaddr_in() | |
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) | |
zeroAddress.sin_family = sa_family_t(AF_INET) | |
guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) { | |
$0.withMemoryRebound(to: sockaddr.self, capacity: 1, { zeroSockAddress in | |
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) | |
}) | |
}) else { | |
return .Unknown | |
} | |
var flags = SCNetworkReachabilityFlags() | |
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { | |
return .Unknown | |
} | |
return ReachabilityStatus(reachabilityFlags: flags) | |
} | |
class func isOnline() -> Bool { | |
let status = self.connectionStatus() | |
switch status { | |
case .Online(.WWAN), .Online(.WiFi): | |
return true | |
case .Offline, .Unknown: | |
return false | |
} | |
} | |
} | |
extension ReachabilityStatus { | |
public init(reachabilityFlags flags: SCNetworkReachabilityFlags) { | |
let connectionRequired = flags.contains(.connectionRequired) | |
let isReachable = flags.contains(.reachable) | |
let isWWAN = flags.contains(.isWWAN) | |
if !connectionRequired && isReachable { | |
if isWWAN { | |
self = .Online(.WWAN) | |
} else { | |
self = .Online(.WiFi) | |
} | |
} else { | |
self = .Offline | |
} | |
} | |
} | |
// works | |
let connectionStatus = Reachability.connectionStatus() | |
switch connectionStatus { | |
case .Online(.WWAN): | |
print("3G/LTE") | |
break | |
default: | |
break | |
} | |
// no worky | |
if connectionStatus == .Online(.WWAN) { | |
// Binary operator '==' cannot be applied to operands of type 'ReachabilityStatus' and '_' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment