Updated @Aaron Brager answer for Swift 4 and Xcode 9.
func getDataUsage() -> (wifi : (sent : UInt32, received : UInt32), wwan : (sent : UInt32, received : UInt32)) {
var interfaceAddresses : UnsafeMutablePointer? = nil
var networkData: UnsafeMutablePointer? = nil
var pointer: UnsafeMutablePointer? = nil
var returnTuple : (wifi : (sent : UInt32, received : UInt32), wwan : (sent : UInt32, received : UInt32)) = ((0, 0), (0, 0))
if getifaddrs(&interfaceAddresses) == 0 {
pointer = interfaceAddresses
while pointer != nil {
let name : String = String.init(validatingUTF8: pointer!.pointee.ifa_name)!
let flags = UInt32((pointer?.pointee.ifa_flags)!)//Int32(pointer?.pointee.ifa_flags)
let addr = pointer?.pointee.ifa_addr.pointee
if addr?.sa_family == UInt8(AF_LINK) {
if name.hasPrefix("en") {
networkData = unsafeBitCast(pointer?.pointee.ifa_data, to: UnsafeMutablePointer.self)
returnTuple.wifi.sent += (networkData?.pointee.ifi_obytes)!
returnTuple.wifi.received += (networkData?.pointee.ifi_ibytes)!
} else if name.hasPrefix("pdp_ip") {
networkData = unsafeBitCast(pointer?.pointee.ifa_data, to: UnsafeMutablePointer.self)
returnTuple.wwan.sent += (networkData?.pointee.ifi_obytes)!
returnTuple.wwan.received += (networkData?.pointee.ifi_ibytes)!
}
}
pointer = pointer?.pointee.ifa_next
}
}
freeifaddrs(interfaceAddresses)
return returnTuple
}