我需要运行一个从每天中午12点开始每24小时重复一次的计时器。找到正确的方法来解决这个问题我遇到了很多麻烦。如果有人可以发布一些示例代码,我会很高兴!
我有它工作我只需要为NSLog输入添加一个计时器。谁能帮我这个?感谢
//假设:targetTime现在已经过去了 NSString * targetTime = @" 12:00&#34 ;;
//split our time into components
NSArray *timeSplit = [targetTime componentsSeparatedByString:@":"];
NSUInteger hours = [[timeSplit objectAtIndex:0] intValue];
NSUInteger minutes = [[timeSplit objectAtIndex:1] intValue];
NSDate *now = [NSDate date];
//split now into year month day components
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [currentCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now];
//set our time components from above
[dateComponents setHour:hours];
[dateComponents setMinute:minutes];
NSDate *targetDate = [currentCalendar dateFromComponents:dateComponents];
//ensure target is after now
if ([targetDate timeIntervalSinceDate:now] < 0)
{
NSDateComponents *day = [[NSDateComponents alloc] init];
[day setDay:1];
targetDate = [currentCalendar dateByAddingComponents:day toDate:targetDate options:0];
}
NSTimeInterval timeRemaining = [targetDate timeIntervalSinceDate:now];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(@"hh:mm:ss %@", formattedDate);
答案 0 :(得分:1)
我觉得你运气不好。当您的应用进入后台时,计时器会失效。您需要检查应用重新进入前台的时间,并启动一个将在中午开火的新计时器。
要在您的应用未运行时触发事件,我认为您能做的最好的是UILocalNotification,它会向用户显示一条消息,并提供调用您应用的选项。
如果您为Jailbroken设备构建应用程序,您可能会这样做,但我对越狱开发一无所知。