首页 > 解决方案 > 在整个应用程序生命周期中运行 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
}

谢谢,

标签: iosswiftbackgroundcllocationmanager

解决方案


使用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


推荐阅读