在后台更新位置不会使应用程序在后台运行后继续运行

时间:2017-11-11 21:27:26

标签: ios swift ios11

我差不多完成了一个基于位置的导航应用程序。它会在收到警报后播放声音,并且在转到谷歌地图时应该在后台保持打开状态,以便在长途旅行或长时间旅行后,他们可以回到应用程序并在他们离开的地方捡起东西。但是,即使我已经定义并请求Location UsageLocation Always Usage,这也不起作用。进入后台后,我可以在Xcode调试器中看到从服务器收到一些指定的JSON,但声音不会播放。此外,如果用户已经离开足够长的时间,即使在控制台中从func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])打印出坐标,那么应用程序将结束并将用户踢回初始视图控制器。我怎么能阻止它?我已经看到其他应用程序在后台保持打开状态,并在iOS中获得一个蓝色状态栏,表示“[此应用程序]正在使用您的位置”。如果我无法让我的应用程序保持打开超过180秒,那么如何保存当前数据以便用户可以从他/她离开的地方恢复?

var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    mapView.showsUserLocation = true
    mapView.delegate = self

    if let userLocation = mapView.userLocation.location { // because sometimes there is no coordinate and it will unwrap nil.
        mapView.centerCoordinate = userLocation.coordinate
        let region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 9484.1, 9484.1)
        mapView.setRegion(region, animated: true)
    }

    UIApplication.shared.isIdleTimerDisabled = true

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

}

func mapView(_ mapView: MKMapView, didUpdate: MKUserLocation) {
    let userLocation = mapView.userLocation
    mapView.centerCoordinate = userLocation.location!.coordinate
    //let region = MKCoordinateRegionMakeWithDistance(frontedUserLocation, 1855, 1855)
    let region = MKCoordinateRegionMakeWithDistance(mapView.centerCoordinate, 9484.1, 9484.1)
    mapView.setRegion(region, animated: true)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let mostRecentLocation = locations.last else {
        return
    }

    // Add another annotation to the map.
    let annotation = MKPointAnnotation()
    annotation.coordinate = mostRecentLocation.coordinate

    // Also add to our map so we can remove old values later

    // Remove values if the array is too big

    if UIApplication.shared.applicationState == .active {

    } else {
        print("App is backgrounded. New location is %@", mostRecentLocation)
        print("Background time remaining = \(UIApplication.shared.backgroundTimeRemaining) seconds")
        if (UIApplication.shared.backgroundTimeRemaining < 175.2) {
            print("Time low. Re-registering...")
            locationManager.stopUpdatingLocation()
            locationManager.startUpdatingLocation()
            self.registerBackgroundTask()
        }
    }
}

/*func operate() {
    //call endBackgroundTask() on completion..
    switch UIApplication.shared.applicationState {
    case .active:
        print("App is active.")
    case .background:
        print("App is in background.")
        print("Background time remaining = \(UIApplication.shared.backgroundTimeRemaining) seconds")
        if (UIApplication.shared.backgroundTimeRemaining < 175.2) {
            print("Time low. Re-registering...")
            self.registerBackgroundTask()
        }
    case .inactive:
        endBackgroundTask()
        self.registerBackgroundTask()
        break
    }
}*/

func updateCoords() {
    let updateCoordinates = CloudOperation() // edit this to accept a different parameter
    let userLocation = self.mapView.userLocation.location!.coordinate
    updateCoordinates.latit = userLocation.latitude
    updateCoordinates.longi = userLocation.longitude
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.pausesLocationUpdatesAutomatically = false
    locationManager.startUpdatingLocation()

    /*backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
        self?.endBackgroundTask()
    }
    assert(backgroundTask != UIBackgroundTaskInvalid)*/

    //self.registerBackgroundTask()
    print("Trying to update...")

    dump(self.phase)
}

谢谢!

Capabilities Capabilities 2

1 个答案:

答案 0 :(得分:1)

请确保您在CLLocationManager

中启用了后台模式
locationManager.allowsBackgroundLocationUpdates = true