Swift version with 5G support; based on several answers.
import Foundation
import SystemConfiguration
import CoreTelephony
/// Returns current network connection type(e.g. 4G, WIFI). It may take some time; so there is the suggestion not to use it on the main queue.
static func connectionType() -> ConnectionType {
guard let reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.google.com") else {
return .noConnection
}
var flags = SCNetworkReachabilityFlags()
SCNetworkReachabilityGetFlags(reachability, &flags)
guard flags.contains(.reachable) else { return .noConnection }
guard flags.contains(.isWWAN) else { return .wifi }
let networkInfo = CTTelephonyNetworkInfo()
let carrierTypeName: String?
if #available(iOS 12.0, *) {
carrierTypeName = networkInfo.serviceCurrentRadioAccessTechnology?.first?.value
} else {
carrierTypeName = networkInfo.currentRadioAccessTechnology
}
if #available(iOS 14.0, *) {
switch carrierTypeName {
case CTRadioAccessTechnologyNR, CTRadioAccessTechnologyNRNSA:
return .cellular5G
default:
break
}
}
switch carrierTypeName {
case CTRadioAccessTechnologyGPRS, CTRadioAccessTechnologyEdge, CTRadioAccessTechnologyCDMA1x:
return .cellular2G
case CTRadioAccessTechnologyLTE:
return .cellular4G
case nil:
return .unknown
default:
return .cellular3G
}
}
enum ConnectionType: CustomStringConvertible {
case noConnection, unknown, wifi, cellular2G, cellular3G, cellular4G, cellular5G
var description: String {
switch self {
case .noConnection:
return "no connection"
case .unknown:
return "unknown"
case .wifi:
return "WIFI"
case .cellular2G:
return "2G"
case .cellular3G:
return "3G"
case .cellular4G:
return "LTE"
case .cellular5G:
return "5G"
}
}
}