我正在开发一个只能在一天中的特定时间使用的应用程序。我无法获取本地设备时间,因为用户可以轻松地更改设备时间,从而允许在一天中的任何时间访问应用程序。
有没有办法从Apple服务器获取当前日期和时间(如果没有),还有其他方法吗?
发布于 2012-01-31 14:53:00
我认为你应该使用互联网时间服务器。他们使用一种称为NTP的标准化协议。iOS具有built-in support for reading NTP server time,但作为应用程序开发人员,您无法访问它。您可以自己实现,也可以使用开源库,如ios-ntp或HS NTP。我自己还没有用过其中任何一个。检查设备的位置并确定时区可能是一个好主意,以获得真正的防弹解决方案。
在这里,您可以阅读更多关于服务器和其他内容的内容;NIST Internet Time Service
理想情况下,应用程序中应该有一个服务器列表。如果其中一个出现故障,您将调用列表中的下一个NTP服务器。
发布于 2012-01-31 14:28:42
- (NSDate *) CurrentDate
{
if ([self hasInternetConnectivity]) // this tests Internet connectivity based off Apple's Reachability sample code
{
NSSURL * scriptUrl = [NSURL URLWithString: @"http:// <yoursite>. Com / <the 2 line php script>. Php"];
NSData * data = [NSData dataWithContentsOfURL: scriptUrl];
if (data! = nil) {
NSString * tempString = [NSString stringWithUTF8String: [data bytes]];
NSDate * currDate = [NSDate dateWithTimeIntervalSince1970: [tempString doubleValue]];
NSLog (@ "String returned from the site is:% @ and date is:% @", tempString, [currDate description]);
return currDate;
}
else {
NSLog (@ "nsdata download failed");
return [NSDate date];
}
}
else {
NSLog (@ "InternetConnectivity failed");
return [NSDate date];
}
}
发布于 2015-09-21 02:00:53
您可以使用该开放源码从默认NTP服务器获取时间,或者选择您的服务器:https://github.com/huynguyencong/NHNetworkTime
[[NHNetworkClock sharedNetworkClock] syncWithComplete:^{
NSLog(@"%s - Time synced %@", __PRETTY_FUNCTION__, [NSDate networkDate]);
}];
并使用:
NSDate *networkDate = [NSDate networkDate];
https://stackoverflow.com/questions/9075303
复制相似问题