5

我创建了在后台运行 NSTimer 的应用程序。我使用位置管理器在后台运行 NSTimer,

我使用下面的链接在后台运行 NSTimer,

如何在我的 iOS 应用程序中每 n 分钟更新一次后台位置?

这种方法在 iOS 6 中运行良好,但在 iOS 7 上不起作用。我的应用程序在 iOS 7 上的后台应用程序在一段时间后崩溃。

如果有任何不同的方法在后台运行 NSTimer,请告诉我。

提前致谢。

4

4 回答 4

5

在 iOS7 中,有一种新的周期性数据获取模式。将fetch后台模式添加到您的应用程序,并在您的应用程序委托中,将间隔传递给- [UIApplication setMinimumBackgroundFetchInterval:. application:performFetchWithCompletionHandler:一旦应用程序处于后台,您的应用程序的代理将开始接收调用。

更多信息在这里: https ://developer.apple.com/library/ios/documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/application:performFetchWithCompletionHandler :

于 2013-09-26T07:32:28.840 回答
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];
于 2016-01-18T07:21:25.617 回答
-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;
}
于 2015-01-03T12:25:28.757 回答
-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;   
}
于 2013-11-29T07:36:27.860 回答