在所有应用程序状态下获取用户当前位置(lat/long),但并非总是在需要我的应用程序而没有位置管理器委托时



我正在开发watch heart beat应用程序,我希望当用户心率危急时,我们会在(前台、后台和终端)中获取他的当前位置,并将其发送到我们的服务器。有没有什么方法可以让我只在那个位置获得用户位置。我不想每次都更新他的位置。

要获得用户位置,必须声明:

let locationManager = CLLocationManager()

在您的控制器中。

然后,在viewDidLoad中,您必须请求位置并初始化CLLocationManager获取过程:

// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization() 
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
}

您将在CLLocationManagerDelegate:中获得位置

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var location:CLLocationCoordinate2D = manager.location.coordinate
    print("locations = (location.latitude) (location.longitude)")
}

在您的info.plist中,您必须添加NSLocationAlwaysUsageDescription和自定义警报消息,以便在请求定位时显示。

欢呼。。。

最新更新