gpt4 book ai didi

ios - 使用 swift 跟踪蜂窝数据使用情况

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:13 25 4
gpt4 key购买 nike

有什么方法可以快速跟踪设备使用的蜂窝数据吗?有没有api我正在尝试实现类似 this 的目标

最佳答案

更新到 Swift 4,您可以使用这个简单的扩展。跟踪设备电池和 wifi 使用情况。

extension SystemDataUsage {

public static var wifiCompelete: UInt64 {
return SystemDataUsage.getDataUsage().wifiSent + SystemDataUsage.getDataUsage().wifiReceived
}

public static var wwanCompelete: UInt64 {
return SystemDataUsage.getDataUsage().wirelessWanDataSent + SystemDataUsage.getDataUsage().wirelessWanDataReceived
}

}

class SystemDataUsage {

private static let wwanInterfacePrefix = "pdp_ip"
private static let wifiInterfacePrefix = "en"

class func getDataUsage() -> DataUsageInfo {
var ifaddr: UnsafeMutablePointer<ifaddrs>?
var dataUsageInfo = DataUsageInfo()

guard getifaddrs(&ifaddr) == 0 else { return dataUsageInfo }
while let addr = ifaddr {
guard let info = getDataUsageInfo(from: addr) else {
ifaddr = addr.pointee.ifa_next
continue
}
dataUsageInfo.updateInfoByAdding(info)
ifaddr = addr.pointee.ifa_next
}

freeifaddrs(ifaddr)

return dataUsageInfo
}

private class func getDataUsageInfo(from infoPointer: UnsafeMutablePointer<ifaddrs>) -> DataUsageInfo? {
let pointer = infoPointer
let name: String! = String(cString: pointer.pointee.ifa_name)
let addr = pointer.pointee.ifa_addr.pointee
guard addr.sa_family == UInt8(AF_LINK) else { return nil }

return dataUsageInfo(from: pointer, name: name)
}

private class func dataUsageInfo(from pointer: UnsafeMutablePointer<ifaddrs>, name: String) -> DataUsageInfo {
var networkData: UnsafeMutablePointer<if_data>?
var dataUsageInfo = DataUsageInfo()

if name.hasPrefix(wifiInterfacePrefix) {
networkData = unsafeBitCast(pointer.pointee.ifa_data, to: UnsafeMutablePointer<if_data>.self)
if let data = networkData {
dataUsageInfo.wifiSent += UInt64(data.pointee.ifi_obytes)
dataUsageInfo.wifiReceived += UInt64(data.pointee.ifi_ibytes)
}

} else if name.hasPrefix(wwanInterfacePrefix) {
networkData = unsafeBitCast(pointer.pointee.ifa_data, to: UnsafeMutablePointer<if_data>.self)
if let data = networkData {
dataUsageInfo.wirelessWanDataSent += UInt64(data.pointee.ifi_obytes)
dataUsageInfo.wirelessWanDataReceived += UInt64(data.pointee.ifi_ibytes)
}
}
return dataUsageInfo
}
}

struct DataUsageInfo {
var wifiReceived: UInt64 = 0
var wifiSent: UInt64 = 0
var wirelessWanDataReceived: UInt64 = 0
var wirelessWanDataSent: UInt64 = 0

mutating func updateInfoByAdding(_ info: DataUsageInfo) {
wifiSent += info.wifiSent
wifiReceived += info.wifiReceived
wirelessWanDataSent += info.wirelessWanDataSent
wirelessWanDataReceived += info.wirelessWanDataReceived
}
}

您可以像这样使用它:SystemDataUsage.wifiCompelete

关于ios - 使用 swift 跟踪蜂窝数据使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25888272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com