简体   繁体   English

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

[英]How to track user location in the background swift

I am trying to track the user location in background I have try using when In us with and without always , but every time I minimise the app the location icon disappear I have read in a tutorial it should show blue bar but I am not getting that bar I have also check the background mode for updating the location 我试图在后台跟踪用户位置,当我们在有和没有的情况下尝试使用时,但是每次我最小化应用程序时,位置图标都消失了,我已经在教程中阅读过它应该显示蓝色条,但我没有得到栏我也检查了背景模式以更新位置

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

You can use startMonitoringSignificantLocationChanges() method instead of startUpdatingLocation() 您可以使用startMonitoringSignificantLocationChanges()方法代替startUpdatingLocation()

Based on docs: 根据文档:

Apps can expect a notification as soon as the device moves 500 meters or more from its previous notification. 当设备距其先前的通知500米或更多距离时,应用程序会期望收到通知。 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. 如果设备能够从网络检索数据,则位置管理器更有可能及时传递通知。

I have used this method once and tested it. 我曾经使用过这种方法并对其进行了测试。 It works well with cellular and wi-fi. 它与蜂窝和wi-fi搭配使用效果很好。

Your question is not clear. 您的问题不清楚。 Do you have problems running your app in background? 您在后台运行应用程序时遇到问题吗? Or do you simple expect the blue bar indicating that your app tracks the location in background? 还是简单地期望蓝色条指示您的应用在后台跟踪位置?

For the latter you need to enable the background location indicator 对于后者,您需要启用后台位置指示器

locationManager.showsBackgroundLocationIndicator = true

这是我一直在寻找的

        locationManager.allowsBackgroundLocationUpdates = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM