2012-06-05 99 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{ 


}