当应用程序进入后台时,计时器swift 3停止运行

时间:2019-04-11 08:58:22

标签: swift location

我有一个应用程序,每10秒运行一次功能,以检测位置并将其发送到网络服务,这会在后台运行时停止工作

   func startBackgroundTask() {
    stopBackgroundTask()
      timer       = Timer.scheduledTimer(timeInterval: 10, target: self, 
    selector: #selector(self.checkLocation), userInfo: nil, repeats: true)
}








   @objc func checkLocation() {

    if UserSA.shared.isArrived == false {

        elapsedTime += 1

        //if self.elapsedTime % 5 == 0 {


      GMSPlacesClient.provideAPIKey(APIKeys.Google.placeAutocomplete)
        GMSServices.provideAPIKey(APIKeys.Google.gmsService)

        placesClient = GMSPlacesClient()

        placesClient.currentPlace(callback: { (placeLikelihoodList, 
  error) -> Void in
            if let error = error {
                print(">>>>>>> GMS Pick Place error: \ 
 (error.localizedDescription)")
                return
            }

            if let placeLikelihoodList = placeLikelihoodList {

                let place = 
    placeLikelihoodList.likelihoods.first?.place
                if let place = place {
                    var params = PositionParamsDTO()

                    params.id = (self.intervention?.id)!

                    self.clientCoordinate?.latitude      = 
         (self.intervention.latitude as NSString).doubleValue
                    self.clientCoordinate?.longitude     = 
      (self.intervention.longitude as NSString).doubleValue

                    params.latitude = place.coordinate.latitude
                    params.longitude = place.coordinate.longitude

                    self.currentCoordinate           = 
   CLLocationCoordinate2D()
                    self.currentCoordinate?.latitude      = 
 place.coordinate.latitude
                    self.currentCoordinate?.longitude     = 
  place.coordinate.longitude

                    InterventionSA.shared.updatePosition(params: 
  params, before: {

                    }, success: { (response) in

                        print(">>>>> position updated ... calcuate 
 artisan distance")
                        //self.checkIfArrived()
                        self.checkIfArrivedBis()

                    }, fail: { (error) in
                        print(">>>>> position update failed")

                    }, done: {

                    })
                }

            }
        })
        //}

    } else {
        timer.invalidate()
        self.performSegue(withIdentifier: Segue.onTheWayToOngoing.key, 
  sender: self)
        //UserSA.shared.isArrived = false
      }

     }

当应用程序进入后台(未终止)时,函数checkLocation停止调用

我该如何进行这项工作?

我也已经激活了后台模式位置更新,后台获取

任何帮助将不胜感激

0 个答案:

没有答案