let locationmanager: CLLocationManager = CLLocationManager()
locationM.delegate = self;
// 请求前台定位授权, 并在Info.Plist文件中配置Key
locationmanager.requestAlwaysAuthorization()
locationmanager.requestWhenInUseAuthorization()
// 设置定位精确度
locationmanager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
// 每隔多少米定位一次
locationmanager.distanceFilter = 5.0
locationmanager.startUpdatingLocation()
}
但是这段代码有个问题,弹出的授权GPS提示框在弹出一秒钟后,又自己消失了,用户没法在如此短时间内进行确认。
找不到原因,猜测这个弹出框的生命周期是否跟locationmanager这个局部变量一样,在代码执行完之后就释放掉。
然后把locationmanager换成属性来使用,问题果然解决了,感觉这又是一个坑。
self.locationmanager = CLLocationManager()
if let locationmanager = self.locationmanager {
locationmanager.requestAlwaysAuthorization()
locationmanager.requestWhenInUseAuthorization()
locationmanager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationmanager.distanceFilter = 5.0
locationmanager.startUpdatingLocation()
}