如何在后台Swift中跟踪用户位置

时间:2018-12-17 11:59:10

标签: ios swift google-maps background userlocation

我试图在后台跟踪用户位置,而在我们中,无论有没有,都总是使用,但是每次我最小化该应用程序时,位置图标都消失了,我已经在教程中阅读过,它应该显示蓝色条,但是我没有得到那个酒吧,我还检查了更新位置的背景模式

  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)")
}

3 个答案:

答案 0 :(得分:1)

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

基于文档:

  

只要设备从先前的通知移开500米或更多,应用程序就会收到通知。它不应期望通知的频率超过每五分钟一次。如果设备能够从网络检索数据,则位置管理器更有可能及时发送通知。

我曾经使用过这种方法并对其进行测试。它可以与蜂窝网络和wi-fi完美配合。

答案 1 :(得分:1)

您的问题不清楚。您在后台运行应用程序时遇到问题吗?还是简单地期望蓝色条指示您的应用在后台跟踪位置?

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

this.paginator.firstPage();

答案 2 :(得分:0)

这就是我想要的

        locationManager.allowsBackgroundLocationUpdates = true