Search code examples
iosunixreboot

How to get iOS reboot times?


The reboot times means when user reboot device, reboot times will accumulate one.

So, is there a way that I can get the reboot times of an iOS device?


Solution

  • Using this method, you can get the time since the system has last rebooted.

    + (time_t)getTimeSinceLastBoot {
        struct timeval boottime;
        int mib[2] = {CTL_KERN, KERN_BOOTTIME};
        size_t size = sizeof(boottime);
        time_t now;
        time_t uptime = -1;
        (void)time(&now);
    
        if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0)
        {
            uptime = now - boottime.tv_sec;
        }
        return uptime;
    }
    

    To get the exact date, you could use the above method as :

        long totalSeconds = [self getTimeSinceLastBoot];
        NSDate *dateNow = [NSDate date];
        NSDate *date = [NSDate dateWithTimeInterval:-totalSeconds sinceDate:dateNow];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
        NSString *dateString = [formatter stringFromDate:date];
    

    By using the above method, you could save the times to somewhere in persistent storage at regular intervals and check every time, If you get the same time next time, that means the device hasn't rebooted. If you get different time, then simply add that time to your database.

    Don't forget to include the below files :

    #include <sys/param.h>
    #include <sys/time.h>
    #include <sys/stat.h>
    #include <sys/sysctl.h>
    #include <sys/proc.h>
    #include <sys/socket.h>