Skip to content

Instantly share code, notes, and snippets.

@meteochu
Created March 6, 2016 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meteochu/e0b20e50f36e09aca512 to your computer and use it in GitHub Desktop.
Save meteochu/e0b20e50f36e09aca512 to your computer and use it in GitHub Desktop.
Quick way to determine current Network Connection Type (Offline, WiFi, or Cellular)
//
// Reachability.swift
//
//
// Created by Andy Liang on 2016-03-06.
// Copyright © 2015 Andy Liang. All rights reserved.
//
import SystemConfiguration
enum ConnectionType {
case Offline
case WiFi
case Cellular
}
struct Reachability {
static func currentConnectionType() -> ConnectionType {
var zeroAddress = sockaddr_in()
bzero(&zeroAddress, sizeofValue(zeroAddress))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return .Offline
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(reachability, &flags) {
return .Offline
}
switch (flags.contains(.Reachable), flags.contains(.IsWWAN)) {
case (false, _):
return .Offline
case (true, true):
return .Cellular
case (true, false):
return .WiFi
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment