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
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 with the following content so that you can use the ObjC class from Swift ( is your project name):
#import "SystemUtil.h"