Skip to content

Instantly share code, notes, and snippets.

@KevinJue
Created March 13, 2015 22:25
Show Gist options
  • Save KevinJue/270a166df990dc83e517 to your computer and use it in GitHub Desktop.
Save KevinJue/270a166df990dc83e517 to your computer and use it in GitHub Desktop.
Detect device connection (WIFI / 3G / 4G ) and retrieve carrier name if needed
import SystemConfiguration
import CoreTelephony
func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false;
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let isWWAN = (flags & UInt32(kSCNetworkReachabilityFlagsIsWWAN)) != 0
if(isReachable || isWWAN){
// Have connection
if (isWWAN){
// Setup the Network Info and create a CTCarrier object
var networkInfo = CTTelephonyNetworkInfo()
var carrier = networkInfo.subscriberCellularProvider
// Get carrier name
var carrierName = carrier.carrierName
}
return true
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment