2016-12-07 90 views
0

我正在編寫一個應用程序,要求每隔n分鐘更新一次位置並將數據發送到服務器,即使應用程序處於後臺模式時也是如此。我已經經歷了這麼多關於這個任務的鏈接。我發現正確的解決方案是使用計時器並將其作爲後臺任務。每n分鐘更新一次背景位置

關於這個我有兩個問題:

  1. 我如何能實現這些常規的背景更新位置?我知道蘋果只能在特定時間內完成後臺任務。那麼如何讓長時間運行的後臺計時器?
  2. 蘋果是否會用這種邏輯拒絕應用程序?
+0

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide /BackgroundExecution/BackgroundExecution.html –

+0

上述鏈接詳細介紹了「跟蹤用戶的位置」 –

回答

1

內的appdelegate中的appdelegate創建方法類似這樣的

 func getLocation() 
     { 
       locationManager.allowsBackgroundLocationUpdates = true 
       locationManager.delegate = self 
       locationManager.desiredAccuracy = kCLLocationAccuracyBest    
       locationManager.startUpdatingLocation() 
     } 

didFinishLaunchingWithOptions方法

var n = 10 //seconds 

var timer = Timer.scheduledTimer(timeInterval: n, target: self, selector: #selector(getLocation), userInfo: nil, repeats: true) 

設置cllocationmanager委託方法

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
    { 
    locationManager.stopUpdatingLocation() 
    locationManager.delegate = nil 
    //get the coordinates or do some code 
    } 
2

使用下面的代碼。此會工作3 minu TES

調用此didenterbackground或前景任何你想要的

var time = 180 
func applicationDidEnterBackground(_ application: UIApplication) 
    { 

     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{ 


} 
+0

下的確切要求,感謝您的回覆。關於您的答案,是否可以延長後臺任務的時間(超過3分鐘),還是由蘋果限制? –

+0

我們不能增加時間,因爲iOS會將應用程序置於暫停狀態。我測試了這個代碼,它將工作180秒 –