【问题标题】:Background task not restarting in Swift后台任务未在 Swift 中重新启动
【发布时间】:2016-11-22 09:36:57
【问题描述】:

我希望每 3 分钟更新一次位置。后台任务第一次在 3 分钟后工作,但在那之后不会重新启动。我需要它重复发生,而不是一次。

override func viewDidLoad()
    {
        super.viewDidLoad()
        timer.invalidate()
        timer = Timer.scheduledTimer(timeInterval: 179, target: self, selector: #selector(someBackgroundTask), userInfo: nil, repeats: true);
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if CLLocationManager.locationServicesEnabled()
        {
            if status == CLAuthorizationStatus.notDetermined
            {
                locationManager.requestAlwaysAuthorization()
            }
        }else {
                print("locationServices disenabled")
            }
            self.locationManager.startUpdatingLocation()
            self.mapView.showsUserLocation = true
            mapView.delegate = self
        registerBackgroundTask()
    }
func someBackgroundTask(timer:Timer) {
        DispatchQueue.global(qos: .background).async {
            self.locationManager.startUpdatingLocation()
            timer.invalidate()
            timer.fire()
            self.registerBackgroundTask()
        }
    }
    func registerBackgroundTask() {
        backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
            self?.someBackgroundTask(timer: (self?.timer)!)
            self?.endBackgroundTask()
        }
        assert(backgroundTask != UIBackgroundTaskInvalid)
    }
    func endBackgroundTask() {
        print("Background task ended.")
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = UIBackgroundTaskInvalid
    }

【问题讨论】:

  • 您不能在后台按时间安排运行任务。您应该启用后台位置更新以在用户移动时接收更新,或者如果您需要更低的准确性和更低的电池影响,则使用重要的位置更新

标签: ios swift function timer background


【解决方案1】:

拨打timer.invalidate 后,您必须再次使用Timer.scheduledTimer(...) 设置计时器。

查看参考https://developer.apple.com/reference/foundation/timer/1415405-invalidate

停止计时器func invalidate() 停止接收器发射 再次请求将其从运行循环中移除。

【讨论】:

    【解决方案2】:

    您需要启用 CLLocationManager 的 allowBackgroundLocationUpdates 。

    在 Swift 2 中,您还需要:

    self.locationManager.allowsBackgroundLocationUpdates = true 
    

    查看更多信息:https://stackoverflow.com/a/36194283/3901620

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2013-12-31
      • 2021-12-26
      相关资源
      最近更新 更多