动机:我正在开发一个应用程序,它可以让多个(客户端)手机从(服务器)手机读取音频数据。这个想法是他们必须在完全相同的时间一起播放这首歌。
前提:我必须想办法让所有手机都以绝对的某个时间戳开始(即它与任何一部手机的使用设置时钟无关等)..根据一些研究,我想出了最好的方法这样做是为了使用CFAbsoluteTimeGetCurrent();
这里的想法是我得到服务器与每部电话通信所需的延迟(b/c GKSession 显然是串行而不是并行完成的),将该延迟添加到当前时间,然后让每部电话从该开始时间开始播放歌曲。这个开始时间必须是绝对的,不能是相对的。
问题:我如何用数字表示未来的时间,以后可以用来构造CFDateRef。(它必须以数字表示的原因是我必须能够以数据包的形式发送它..)
示例:这是一段代码,解释了我想要实现的目标:
-(void)viewDidLoad
{
_timer = [Timer new];
[_timer setCurrentTimeAsReferencepoint];
[self performSelector:@selector(performAction) withObject:NULL afterDelay:5];
}
-(void)performAction
{
double diff = [_timer getTimeElapsedinAbsTime];
double timeInFuture = diff + [Timer getCurTime];
NSLog(@"this is time in future in abs terms %f",timeInFuture);
CFDateRef futureDate = CFDateCreate(NULL, timeInFuture);
CFDateRef dateNow = CFDateCreate(NULL, [Timer getCurTime]);
Boolean keepTesting = true;
while (keepTesting) {
if (CFDateCompare(dateNow, futureDate,NULL) == 0) // ie both times are equal
{
NSLog(@"now is the time!");
keepTesting = false;
} else {
NSLog(@"now isn't the time.. skip");
}
}
}
在 Timer.m 中:
-(void)setCurrentTimeAsReferencepoint
{
_referencePoint = [[self class] getCurTime];
NSLog(@"this is reference point %f",_referencePoint);
}
+(double)getCurTime
{
return (double)CFAbsoluteTimeGetCurrent();
}
// not used in the above code.. but used when i compare the time of the server phone with the client phone
+(double)getTimeDifference:(double)time1
time2:(double)time2
{
CFDateRef newDate = CFDateCreate(NULL, time2);
CFDateRef oldDate = CFDateCreate(NULL, time1);
CFTimeInterval difference = CFDateGetTimeIntervalSinceDate(newDate, oldDate);
NSLog(@"this is time difference %f",fabs(difference));
CFRelease(oldDate); CFRelease(newDate);
// fabs = absolute value
return fabs(difference);
}