
112
|
第
3
章
有时,你只需要获得用户当前位置,并不想在一段时间内跟踪它的位置。要
想这样,你可以用
CLLocationManager
的
requestLocation
方法:
locationManager.requestLocation()
这样个方法并不会返回一个
location
对象,而是立即返回,只有当它获取到
当前位置后,才会通过委托方法通知你,和你使用
startRequestingLocation
是一样的。二者的不同在于,
requestLocation
得到的是单个的
location
对象,
然后就关闭定位。
3.12
计算运动速度
问题
如何得知用户移动的速度?
解决方案
我们可以利用
Core Location
框架来得到答案。
首先,创建一个
CLLocationManager
,如前一节中所述的一样。然后在接收位置变
化通知的方法中:
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
guard let lastLocation = locations.last else {
return
}
if lastLocation.speed > 0 {
self.speedLabel.text = String(
format: "Currently moving at %.0f meters/second",