ios - 在整个应用程序生命周期中运行 CLLocation
问题描述
我可以打开位置服务并让它们在全球范围内运行,而不必在每个 UIViewController 中都打开它吗?我知道它不节能,但我希望定位服务在整个应用程序中运行,而不是在每个控制器中打开它们。一个原因是我发现当我这样做时locationManager.startUpdatingLocation
,位置最初不太准确,然后会收敛到更准确的位置。
理想情况下:它会像这样工作:
class AppDelegate: UIResponder, UIApplicationDelegate {
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
/// LOCATION MANAGER
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
然后在我的应用程序中我想调用的任何地方:
if let location = locationManager.location {
// get the location info immediately
}
谢谢,
解决方案
使用Singletons
,您可以在代码中的任何位置使用位置。单例对象应该只创建一次,然后在需要使用的任何地方共享。您可以创建一个单独的类来访问位置
import Foundation
import CoreLocation
class LocationSyncManager, CLLocationManagerDelegate {
static let shared = LocationSyncManager()
var locationManager: CLLocationManager!
private init(){}
func requestForLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
//add delegate methods
}
你可以访问它AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
LocationSyncManager.shared.requestForLocation()
}
}
您也可以参考:https ://medium.com/@nimjea/singleton-class-in-swift-17eef2d01d88
推荐阅读
- python-3.x - LineString - 获取坐标作为 DataFrame
- ruby - 在 Windows 10 中安装 ruby 2.6.5
- python - 分配某个变量,然后将值分配给嵌套字典而不修改原始变量
- flutter - 颤振/飞镖 - '列表
' 不是类型 'List 的子类型 ' - javascript - 使用 vuetify 格式化表头中的指数数
- python - 如何在字典和 google protobuf 枚举中使用类型提示?
- mysql - 将值插入到mysql中的表时如何处理换行符
- exiftool - 使用 -t 或 -T 选项时 exiftool 不显示空格字符
- php - 如何允许我的 PHP 应用程序写入 AWS 上的文件?
- r - 如何获得不显示列类型的 paged_table?