Skip to content

Instantly share code, notes, and snippets.

@foreignfilm
Last active October 1, 2015 03:00
Show Gist options
  • Save foreignfilm/89c4cad34e2c42e715c9 to your computer and use it in GitHub Desktop.
Save foreignfilm/89c4cad34e2c42e715c9 to your computer and use it in GitHub Desktop.
//
// Reachability.swift
//
// The MIT License (MIT)
// Copyright © 2015 Arnold Sakhnov
//
// Super simple Swift 2.0 struct for your basic Rechability needs
// Use it like so:
//
// if (Rechability.isCurrentlyConnected) { ... }
//
// or:
//
// let currentlyConnected = Rechability.isCurrentlyConnected
// if (currentlyConnected.viaWiFi) { ... }
// else if (currentlyConnected.viaCellular) { ... }
//
import Foundation
import SystemConfiguration
struct Reachability {
struct ConnectionStatus: BooleanType {
let isConnected: Bool
let viaWiFi: Bool
let viaCellular: Bool
var boolValue: Bool {
return isConnected
}
}
static var isCurrentlyConnected: ConnectionStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
var flags = SCNetworkReachabilityFlags.ConnectionAutomatic
let routeReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
guard let reachability = routeReachability where SCNetworkReachabilityGetFlags(reachability, &flags) else {
return ConnectionStatus(isConnected: false, viaWiFi: false, viaCellular: false)
}
let isReachable = (flags.rawValue & SCNetworkReachabilityFlags.Reachable.rawValue) != 0
let needsConnection = (flags.rawValue & SCNetworkReachabilityFlags.ConnectionRequired.rawValue) != 0
let isConnected = (isReachable && !needsConnection)
guard isConnected else {
return ConnectionStatus(isConnected: isConnected, viaWiFi: false, viaCellular: false)
}
let isOnCellular = (flags.rawValue & SCNetworkReachabilityFlags.IsWWAN.rawValue) != 0
return ConnectionStatus(isConnected: isConnected, viaWiFi: !isOnCellular, viaCellular: isOnCellular)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment