Getting system uptime in iOS/Swift

前端 未结 4 1201
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 00:03

Is there a way to get system uptime in iOS (using Swift)? What I need is to measure time without having to worry about the user changing the time. In Android there\'s a

4条回答
  •  醉酒成梦
    2020-12-10 00:18

    You can call ObjC code from Swift:

    print(SystemUtil().uptime());
    

    Write a ObjC class like the accepted answer you mentioned: Getting iOS system uptime, that doesn't pause when asleep.

    SystemUtil.h for interface:

    #import 
    
    @interface SystemUtil : NSObject
    
    - (time_t)uptime;
    
    @end
    

    SystemUtil.m for implementation:

    #import "SystemUtil.h"
    #include 
    
    @implementation SystemUtil
    
    - (time_t)uptime
    {
        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;
    }
    
    @end
    

    And don't forget to include a -Bridge-Header.h with the following content so that you can use the ObjC class from Swift ( is your project name):

    #import "SystemUtil.h"
    

提交回复
热议问题