swift 应用程序启动时多次调用LocationManager

h43kikqp  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(164)

因此,我正在处理一个问题,即我所拥有的LocationManager文件和didUpdateLocations函数在应用程序启动时被多次调用,我无法找出导致此问题的原因。
所以我有下面的LocationManager

import Foundation
import CoreLocation
import MapKit

final class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    
    @Published var userLocation: CLLocation?
    @Published var defaultRegion: MKCoordinateRegion?
    @objc static let getInstance = LocationManager()
    private let locationManager = CLLocationManager()

    override init() {
        super.init()
        locationManager.delegate = self
        log.info("\n 🟢: (LocationManager) - Initialize Location Services inside init()")
    }
    
    func startUpdatingLocation() {
      locationManager.delegate = self
      locationManager.requestWhenInUseAuthorization()
      locationManager.startUpdatingLocation()
    }
    
    func requestLocation() {
        locationManager.requestLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        DispatchQueue.main.async {
            self.userLocation = location
            log.info("\n 🟡: (LocationManager) - Setup new location as: \(location)")
            self.defaultRegion = MKCoordinateRegion(center: location.coordinate, span: USER_LOCATION_SPAN)
            log.info("\n 🟡: (LocationManager) - Setup default region as \(location.coordinate.latitude) and \(location.coordinate.longitude).")
            self.locationManager.stopUpdatingLocation()
            log.info("\n 🟡: (LocationManager) - Stop updating the location.")
        }
    }
}

然后,我在两个名为MapUIViewMapUIView2的单独视图文件中使用它,并且在这两个文件中都有以下对象:
@ObservedObject var locationManager = LocationManager.getInstance
这会导致didUpdateLocations中的DispatchQueue.main.async在应用程序启动时运行两次-这是正常行为吗?或者,didUpdateLocations是否可能只运行一次,但处理多个视图?

0yg35tkg

0yg35tkg1#

locationManager.startUpdatingLocation()用于获取位置流。
locationManager.requestLocation()获取单个位置。只需交换这两个位置。
https://developer.apple.com/documentation/corelocation/cllocationmanager/1620548-requestlocation
但是,由于您似乎正在使用SwiftUI,您也可以考虑

LocationButton(.currentLocation) {
  // Fetch location with Core Location.
}
.symbolVariant(.fill)
.labelStyle(.titleAndIcon)

https://developer.apple.com/documentation/corelocationui/locationbutton

相关问题