如何在后台跟踪用户位置 swift

How to track user location in the background swift

我正在尝试在后台跟踪用户位置 我曾尝试在 In us with 和 without always 时使用,但每次我最小化应用程序时,位置图标都会消失 我在教程中读过它应该显示蓝色条但是我没有得到那个栏我还检查了更新位置的后台模式

  map.showsUserLocation = true
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    // Do any additional setup after loading the view, typically from a nib.
    alwaysAuthorization()
}

func alwaysAuthorization(){
    if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
        locationManager.requestAlwaysAuthorization()
    }
}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last
    let region  = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude), span: MKCoordinateSpan (latitudeDelta: 0.2, longitudeDelta: 0.2))
    self.map.region = region
    print("location \(location!.coordinate.latitude) and \(location!.coordinate.longitude)")
}

您可以使用 startMonitoringSignificantLocationChanges() 方法代替 startUpdatingLocation()

基于文档:

Apps can expect a notification as soon as the device moves 500 meters or more from its previous notification. It should not expect notifications more frequently than once every five minutes. If the device is able to retrieve data from the network, the location manager is much more likely to deliver notifications in a timely manner.

这个方法我用过一次,也测试过。它适用于蜂窝网络和 Wi-Fi。

你的问题不清楚。您的应用在后台有问题 运行 吗?或者您只是希望蓝色条指示您的应用程序在后台跟踪位置?

对于后者,您需要启用后台位置指示器

locationManager.showsBackgroundLocationIndicator = true

这正是我要找的

        locationManager.allowsBackgroundLocationUpdates = true