【问题标题】:How can i update location manager and a timer in my app when it goes to background mode?当应用程序进入后台模式时,如何更新位置管理器和计时器?
【发布时间】:2012-02-11 05:37:43
【问题描述】:

我有一个计时器,它显示用户锻炼的 NSTime。当我的应用程序进入后台模式时,位置管理器和计时器停止更新。当我的应用程序处于后台模式时,如何让它们更新?

我有一个名为 RunViewController 的视图,它有开始按钮。当用户单击该按钮时,计时器和位置管理器将启动。代码是:

 -(void)startRun{
    timeSec = 0;
    timeMin = 0;
    timeHour = 0;

    NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d:%02d",timeHour , timeMin, timeSec];
    //Display on your label
    lblTime.text = timeNow;

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

    self.locManager = [[CLLocationManager alloc] init];
    locManager.delegate = self;
    locManager.desiredAccuracy = kCLLocationAccuracyBest; //kCLLocationAccuracyBest
    [locManager setDistanceFilter:3]; //kCLDistanceFilterNone

    [locManager startUpdatingLocation];
    locationManagerStartDate = [[NSDate date] retain];


}

在 - (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

只需在地图上从旧位置到新位置绘制一条线并将该位置保存在一个数组中。

提前致谢。

【问题讨论】:

  • 发布您的一些代码。还发布位置更新管理器代码

标签: iphone objective-c ios nstimer cllocationmanager


【解决方案1】:

试试这个..

-(void)viewDidLoad
{
    UIDevice* device = [UIDevice currentDevice];
    BOOL backgroundSupported = NO;
    if ([device respondsToSelector:@selector(isMultitaskingSupported)])
        backgroundSupported = device.multitaskingSupported;

    NSLog(backgroundSupported ? @"Yes" : @"No");


    counterTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
     //called after 10min of your app in background
        NSLog(@"10 minutes finished.");
    }];

    theTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(selectorForUpdatingLocation) userInfo:nil repeats:YES];

}

【讨论】:

    【解决方案2】:

    在 Apple 开发者论坛的帮助下找到了实现这一点的解决方案。我做了以下事情:

    • 指定位置背景模式

    • 使用 NSTimer 在后台使用

    • UIApplication:beginBackgroundTaskWithExpirationHandler:万一n为

    小于 UIApplication:backgroundTimeRemaining 它确实有效 很好,如果 n 较大,则应启用位置管理器 (并禁用)在没有剩余时间之前再次避免 后台任务被杀死。这确实有效,因为位置是其中之一 三种允许的后台执行类型。

    注意:通过在模拟器中测试它确实浪费了一些时间,它不起作用,在我的手机上可以正常工作。

    Here 是相同的参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多