我创建了在后台运行NSTimer的Application。我使用位置管理器在后台运行NSTimer,
我使用下面的链接在后台运行NSTimer,
How do I get a background location update every n minutes in my iOS application?
这种方法在iOS 6中运行良好但在iOS 7上无效。我的应用程序在iOS 7的后台应用程序运行一段时间后崩溃。
如果有任何不同的方法在后台运行NSTimer ,请告诉我。
提前致谢。
答案 0 :(得分:5)
在iOS7中,有一种定期数据提取的新模式。将fetch
后台模式添加到您的应用程序,并在您的应用程序委托中,将间隔传递给- [UIApplication setMinimumBackgroundFetchInterval:
。一旦应用程序在后台,您的应用程序代理将开始接听application:performFetchWithCompletionHandler:
的电话。
答案 1 :(得分:2)
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
loop = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(Update) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:loop forMode:NSRunLoopCommonModes];
答案 2 :(得分:-1)
NSTimer *currentCycleTimer;
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
[currentCycleTimer invalidate];
currentCycleTimer=nil;
secondsLeft = 120;
currentCycleTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(Countdown) userInfo:nil repeats: YES];
-(void) Countdown
{
[currentCycleTimer invalidate];
currentCycleTimer=nil;
}
答案 3 :(得分:-2)
-(void)start {
[[NSUserDefaults standardUserDefaults ]setObject:[NSDate date] forKey:@"startTimer"];
Nstimer* timer2=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}
-(void)timerFired
{
@try {
NSDate *timerStartDate = [[NSUserDefaults standardUserDefaults]objectForKey:@"startTimer"];
NSTimeInterval interval=[timerStartDate timeIntervalSinceNow];
int hour1=-interval/3600;
int rem =((int)interval)%3600 ;
int min1 = -rem/60 ;
int sec1 = -rem %60 ;
// NSLog(@"hour %i rem %i",hour,rem);
// NSLog(@"hour%i",hour1);
// NSLog(@"min%i",min1);
// NSLog(@"sec%i",sec1);
NSString *strmin=[NSString stringWithFormat:@"%i",min1];
NSString *strhour=[NSString stringWithFormat:@"%i",hour1];
if ([strmin integerValue]<10)
{
[lblSeconds setText:[NSString stringWithFormat:@"0%@",strmin]];
}
else
{
lblSeconds.text=strmin;
}
if ([strhour integerValue]<10) {
[lblHour setText:[NSString stringWithFormat:@"0%@",strhour]];
}
else
{
lblHour.text=strhour;
}
}
@catch (NSException *exception) {
NSLog(@"exception in timer %@ ",[exception description]);
}
return;
}