Created
March 6, 2016 08:10
-
-
Save meteochu/e0b20e50f36e09aca512 to your computer and use it in GitHub Desktop.
Quick way to determine current Network Connection Type (Offline, WiFi, or Cellular)
This file contains 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 | |
// | |
// | |
// 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