2012-06-05 57 views
0

我想打,更新用户的位置,以我的远程服务器中的每XX分钟的更新应用程序的位置,即使该应用程序在后台 我曾尝试下面的代码后台任务或iphone

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    i=0; 
    UIApplication *app = [UIApplication sharedApplication]; 
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
     [app endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }]; 
    bgTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundTask:) userInfo:nil repeats:YES]; 

} 

-(void)backgroundTask:(NSTimer*)timer{ 

    i++; 
    NSLog(@"%s %d",__func__,i); 
} 

但大约10分钟后,计时器回调停止 我怎样才能让连续到我的服务器更新当前位置的应用程序

回答

3

你可能丢失在您的应用程序的Info.plist文件中背景模式键:

<key>UIBackgroundModes</key> 
    <array> 
      <string>location</string> 
    </array> 

这可让您的应用在后台访问位置服务。

但是,这种类型的东西已被询问了很多次,所以也做了一些浏览other stack overflow questions的更多信息。

Here's another one要阅读。

0

可以在后台只有3 minutes.Set Capabilities-> BackgroundFetch上使用下面的代码

调用此didenterbackground或前景以上或等于大于3场 更新

var time = 120 
func applicationDidEnterBackground(_ application: UIApplication) 
    { 
     time = 180 
     self.doBackgroundTask() 
    } 

var timerBack = Timer() 
    func doBackgroundTask() { 

     DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { 
      self.beginBackgroundUpdateTask() 


      self.timerBack = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.displayAlert), userInfo: nil, repeats: true) 
      RunLoop.current.add(self.timerBack, forMode: RunLoopMode.defaultRunLoopMode) 
      RunLoop.current.run() 

      self.endBackgroundUpdateTask() 
     } 
    } 
    var backgroundUpdateTask: UIBackgroundTaskIdentifier! 

    func beginBackgroundUpdateTask() { 
     self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: { 
      self.endBackgroundUpdateTask() 
     }) 
    } 

    func endBackgroundUpdateTask() { 
     UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask) 
     self.backgroundUpdateTask = UIBackgroundTaskInvalid 
    } 

//完成无论你想要什么

func displayAlert{ 


}