3

how can i get the boot time of ios in objective c ?

Is there a way to get it?

Kai
  • 38,985
  • 14
  • 88
  • 103
Y2theZ
  • 10,162
  • 38
  • 131
  • 200

2 Answers2

12

Don't know if this will work in iOS, but in OS X (which is essentially the same OS) you would use sysctl(). This is how the OS X Unix utility uptime does it. Source code is available - search for "boottime".

#include <sys/types.h>
#include <sys/sysctl.h>  

// ....  

#define MIB_SIZE 2  

int mib[MIB_SIZE];
size_t size;
struct timeval  boottime;

mib[0] = CTL_KERN;
mib[1] = KERN_BOOTTIME;
size = sizeof(boottime);
if (sysctl(mib, MIB_SIZE, &boottime, &size, NULL, 0) != -1)
{
    // successful call
    NSDate* bootDate = [NSDate dateWithTimeIntervalSince1970:boottime.tv_sec];
}

The restricted nature of programming in the iOS sandboxed environment might make it not work, I don't know, I haven't tried it.

Felix
  • 35,354
  • 13
  • 96
  • 143
JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • 1
    There are apps in the App Store that are using sysctl functionality. Doesn't necessarily mean this would be allowed though. – mttrb Apr 26 '12 at 10:56
  • 2
    seems to work, I edited the answer to show how to get it as NSDate – Felix Apr 26 '12 at 12:55
  • 2
    It is absolutely allowed on the app store – Dickey Singh Jun 20 '14 at 17:24
  • A good reason to use it: boot time changes obviously when you reboot, but also if the user changes the clock. So to check that your time is reliable, you store the last known boot time in preferences, and if that time changes, who can check with a time server whether the time is ok. iOS keeps the "seconds since boot" unchanged except for the obvious change of one second each second, even when you change the clock in settings. – gnasher729 Apr 12 '23 at 16:37
1

I took JeremyP's answer, gave the result the full microsecond precision, clarified the names of local variables, improved the order, and put it into a method:

#include <sys/types.h>
#include <sys/sysctl.h>  

// ....  

+ (nullable NSDate *)bootDate
{
    // nameIntArray and nameIntArrayLen
    int nameIntArrayLen = 2;
    int nameIntArray[nameIntArrayLen];
    nameIntArray[0] = CTL_KERN;
    nameIntArray[1] = KERN_BOOTTIME;

    // boot_timeval
    struct timeval boot_timeval;
    size_t boot_timeval_size = sizeof(boot_timeval);
    if (sysctl(nameIntArray, nameIntArrayLen, &boot_timeval, &boot_timeval_size, NULL, 0) == -1)
    {
        return nil;
    }

    // bootSince1970TimeInterval
    NSTimeInterval bootSince1970TimeInterval = (NSTimeInterval)boot_timeval.tv_sec + ((NSTimeInterval)boot_timeval.tv_usec / 1000000);

    // return
    return [NSDate dateWithTimeIntervalSince1970:bootSince1970TimeInterval];
}
John Bushnell
  • 1,851
  • 22
  • 29