我正在开发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
和自定义警报消息,以便在请求定位时显示。
欢呼。。。