2

I get from my app internet data how much I used internet data after restart a device. I want to clear this data after when I will touch a button. How can I make it? I use swift. This code with help I get internet data. This code is from Tracking iPhone Data Usage:

 func getDataUsage() -> (wifi : (sent : UInt32, received : UInt32), wwan : (sent : UInt32, received : UInt32)) {
    var interfaceAddresses : UnsafeMutablePointer<ifaddrs> = nil
    var networkData: UnsafeMutablePointer<if_data> = nil

    var returnTuple : (wifi : (sent : UInt32, received : UInt32), wwan : (sent : UInt32, received : UInt32)) = ((0, 0), (0, 0))

    if getifaddrs(&interfaceAddresses) == 0 {
        for var pointer = interfaceAddresses; pointer != nil; pointer = pointer.memory.ifa_next {

            let name : String! = String.fromCString(pointer.memory.ifa_name)
            print(name);
            // changed it
            _ = Int32(pointer.memory.ifa_flags)
            let addr = pointer.memory.ifa_addr.memory
            //
            if addr.sa_family == UInt8(AF_LINK) {
                if name.hasPrefix("en") {
                    networkData = unsafeBitCast(pointer.memory.ifa_data, UnsafeMutablePointer<if_data>.self)
                    returnTuple.wifi.sent += networkData.memory.ifi_obytes
                    returnTuple.wifi.received += networkData.memory.ifi_ibytes
                } else if name.hasPrefix("pdp_ip") {
                    networkData = unsafeBitCast(pointer.memory.ifa_data, UnsafeMutablePointer<if_data>.self)
                    returnTuple.wwan.sent += networkData.memory.ifi_obytes
                    returnTuple.wwan.received += networkData.memory.ifi_ibytes
                }
            }
        }

        freeifaddrs(interfaceAddresses)
    }

    return returnTuple
}
Community
  • 1
  • 1
Alexander Khitev
  • 6,417
  • 13
  • 59
  • 115

1 Answers1

2

I would proceed as follows:

  • When the "Clear" button is pressed, retrieve the current usage values and store them in the user defaults.

  • For display, compute the difference between the current values and the values in the user defaults.

  • To detect if the device has rebooted, get the kernel boot time (e.g. in didFinishLaunchingWithOptions) and compare it with the last stored value. If it is different, reset the stored usage data in the user defaults, and store the new kernel boot time in the user defaults.

The kernel boot time can be retrieved with the following function (which is just a translation of the code in Getting iOS system uptime, that doesn't pause when asleep to Swift):

func bootTime() -> Int {

    var boot = timeval()
    var mib : [Int32] = [CTL_KERN, KERN_BOOTTIME]
    var size = strideofValue(boot)
    sysctl(&mib, UInt32(mib.count), &boot, &size, nil, 0)
    return boot.tv_sec
}
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382