79324492

Date: 2025-01-02 17:26:35
Score: 1
Natty:
Report link

I realized the accepted answer (from @BilalReffas) has a memory leak issue. See the following demonstration:

struct ContentView: View {
    @State private var wifiUsage: Double = 0.0
    @State private var wwanUsage: Double = 0.0
    
    var body: some View {
        VStack(spacing: 20) {
            Text("Data Usage")
                .font(.headline)
            
            Text("WiFi: \(wifiUsage, specifier: "%.2f") MB")
            Text("WWAN: \(wwanUsage, specifier: "%.2f") MB")
        }
        .padding()
        .onAppear {
            Timer.scheduledTimer(withTimeInterval: 0.01 , repeats: true) { _ in
                wifiUsage = Double(SystemDataUsage.wifiCompelete) / 1_048_576.0
                wwanUsage = Double(SystemDataUsage.wwanCompelete) / 1_048_576.0
            }
        }
    }
}

Which shows the memory usage exploding over time (I intentionally rerun the function every 10ms to demonstrate the behavior).

enter image description here

After searching around, the following improvement for func getDataUsage() fixed the issue.

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

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

    freeifaddrs(ifaddr) // Correctly free the allocated memory after iteration
    return dataUsageInfo
}

enter image description here

Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @BilalReffas
  • Low reputation (0.5):
Posted by: Khashayar