【发布时间】:2018-07-18 06:28:30
【问题描述】:
我有一个应用程序可以间隔提供数据使用。我想在使用数据使用之前检测设备是否已重新启动。我尝试使用 mach_absolute_time() 但我什么都听不懂。这可能吗?
【问题讨论】:
标签: ios
我有一个应用程序可以间隔提供数据使用。我想在使用数据使用之前检测设备是否已重新启动。我尝试使用 mach_absolute_time() 但我什么都听不懂。这可能吗?
【问题讨论】:
标签: ios
您可以像这样获得系统正常运行时间:
let systemUptime = NSProcessInfo.processInfo().systemUptime; // swift
NSTimeInterval timeInterval = [NSProcessInfo processInfo].systemUptime; //Objective c
您可以将其存储在 NSUserDefaults 中并使用它来确定是否发生了重启。
请查看this 线程以获取更多信息。
斯威夫特 3:
let systemUptime: TimeInterval = ProcessInfo.processInfo.systemUptime
【讨论】:
这是我制作的。它需要 GMT 的当前时间和自上次重新启动以来的时间来推断设备上次重新启动的日期。然后它使用 NSUserDefaults 在内存中跟踪这个日期。享受吧!
#define nowInSeconds CFAbsoluteTimeGetCurrent()//since Jan 1 2001 00:00:00 GMT
#define secondsSinceDeviceRestart ((int)round([[NSProcessInfo processInfo] systemUptime]))
#define storage [NSUserDefaults standardUserDefaults]
#define DISTANCE(__valueOne, __valueTwo) ((((__valueOne)-(__valueTwo))>=0)?((__valueOne)-(__valueTwo)):((__valueTwo)-(__valueOne)))
+(BOOL)didDeviceReset {
static BOOL didDeviceReset;
static dispatch_once_t onceToken;
int currentRestartDate = nowInSeconds-secondsSinceDeviceRestart;
int previousRestartDate = (int)[((NSNumber *)[storage objectForKey:@"previousRestartDate"]) integerValue];
int dateVarianceThreshold = 10;
dispatch_once(&onceToken, ^{
if (!previousRestartDate || DISTANCE(currentRestartDate, previousRestartDate) > dateVarianceThreshold) {
didDeviceReset = YES;
} else {
didDeviceReset = NO;
}
});
[storage setObject:@(currentRestartDate) forKey:@"previousRestartDate"];
[storage synchronize];
return didDeviceReset;
}
【讨论】:
-[NSUserDefaults synchronize]。来自Apple's documentation“这个方法是不必要的,不应该使用。”。另外,不要对多个问题给出相同的答案。只需在 cmets 中提供一个链接。 stackoverflow.com/a/51391327/123632