swift - 为什么这个 Singleton Location Manager 类返回 nil Location?
问题描述
我正在尝试在我的项目中使用LocationSingleton
Class
此博客中的以下内容。我喜欢它的简单用法。
您只需调用以下命令即可开始更新位置:
LocationSingleton.sharedInstance.startUpdatingLocation()
只需调用即可获取最后一个位置:
LocationSingleton.sharedInstance.lastLocation
我的意图是启动位置服务,获取最后一个位置,以便我可以使用返回的位置从 Firebase 获取用户。
问题是,如果我lastLocation
startUpdatingLocation
在它返回后直接nil
调用。
经过一些调试,我发现原因是因为位置服务在设备上启动速度很慢,因此在lastLocation
调用时设备尚未获取位置。我想lastLocation
在记录后立即执行下一个命令。我怎样才能做到这一点?
我想了解如何Protocol
使用?
import UIKit
import CoreLocation
protocol LocationServiceDelegate {
func locationDidUpdateToLocation(currentLocation: CLLocation)
func locationUpdateDidFailWithError(error: NSError)
}
class LocationSingleton: NSObject,CLLocationManagerDelegate {
var locationManager: CLLocationManager?
var lastLocation: CLLocation?
var delegate: LocationServiceDelegate?
static let sharedInstance:LocationSingleton = {
let instance = LocationSingleton()
return instance
}()
override init() {
super.init()
self.locationManager = CLLocationManager()
guard let locationManagers=self.locationManager else {
return
}
if CLLocationManager.authorizationStatus() == .notDetermined {
//locationManagers.requestAlwaysAuthorization()
locationManagers.requestWhenInUseAuthorization()
}
if #available(iOS 9.0, *) {
// locationManagers.allowsBackgroundLocationUpdates = true
} else {
// Fallback on earlier versions
}
locationManagers.desiredAccuracy = kCLLocationAccuracyBest
locationManagers.pausesLocationUpdatesAutomatically = false
locationManagers.distanceFilter = 0.1
locationManagers.delegate = self
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
self.lastLocation = location
updateLocation(currentLocation: location)
}
@nonobjc func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
locationManager?.requestWhenInUseAuthorization()
break
case .authorizedWhenInUse:
locationManager?.startUpdatingLocation()
break
case .authorizedAlways:
locationManager?.startUpdatingLocation()
break
case .restricted:
// restricted by e.g. parental controls. User can't enable Location Services
break
case .denied:
// user denied your app access to Location Services, but can grant access from Settings.app
break
default:
break
}
}
// Private function
private func updateLocation(currentLocation: CLLocation){
guard let delegate = self.delegate else {
return
}
delegate.locationDidUpdateToLocation(currentLocation: currentLocation)
}
private func updateLocationDidFailWithError(error: NSError) {
guard let delegate = self.delegate else {
return
}
delegate.locationUpdateDidFailWithError(error: error)
}
func startUpdatingLocation() {
print("Starting Location Updates")
self.locationManager?.startUpdatingLocation()
// self.locationManager?.startMonitoringSignificantLocationChanges()
}
func stopUpdatingLocation() {
print("Stop Location Updates")
self.locationManager?.stopUpdatingLocation()
}
func startMonitoringSignificantLocationChanges() {
self.locationManager?.startMonitoringSignificantLocationChanges()
}
}
解决方案
位置管理器异步工作并提供委托方法来获取结果。
在您的类中采用LocationServiceDelegate
,实现委托方法并设置委托,例如viewDidLoad
func locationDidUpdateToLocation(currentLocation: CLLocation)
{
print(LocationSingleton.sharedInstance.lastLocation)
}
func locationUpdateDidFailWithError(error: NSError)
{
print(error)
}
func viewDidLoad()
super viewDidLoad()
let locationSingleton = LocationSingleton.sharedInstance
locationSingleton.delegate = self
locationSingleton.startUpdatingLocation()
}
当检测到位置时,调用其中一个委托方法
推荐阅读
- c - 如何在 C 中向量化和优化这些函数?
- arrays - 反应原生状态图。如何只渲染 1 个值?
- python - 如何使用 Pandas 或 Numpy 计算离散时间序列的“倍增时间”?
- android - Android Studio 在使用变量时不会对依赖项给出新版本警告?
- amazon-web-services - AWS Amplify 自定义解析程序 - 不支持的操作“BatchPutItem”
- vue.js - vform multiselected 下拉默认选中并期望出现数组错误
- react-native - 如何解决测试中的 NativeModule.RNLocalize is null 错误?
- c - 使用 MPI (C) 的产品矩阵向量 - 无法正常工作
- wordpress - 在新域上使用 .htaccess 重定向以链接 Wordpress 页面
- excel - 使用后组合框列表中的项目变灰,因此用户无法选择它们