//创建通知监听(判断游戏时长)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; //监听是否重新进入程序程序.
#pragma mark - 实现2个NSNotificationCenter所触发的事件方法
//回到后台都视为一次会话结束(计时end)
+ (void)applicationWillResignActive:(NSNotification *)notification
{
NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
long long int date = (long long int)time;
NSString * timeStr = [NSString stringWithFormat:@"%lld",date];
NSLog(@"后台:timestr :%@ ",timeStr);
}
//回到前台都视为一次新启动(计时start)
+ (void)applicationDidBecomeActive:(NSNotification *)notification
{
NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
long long int date = (long long int)time;
NSString * timeStr = [NSString stringWithFormat:@"%lld",date];
NSLog(@"前台:timestr :%@ ",timeStr);
}
再将两个时间相减可得出游戏时长。