因此,我正在处理一个问题,即我所拥有的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.")
}
}
}
然后,我在两个名为MapUIView
和MapUIView2
的单独视图文件中使用它,并且在这两个文件中都有以下对象:@ObservedObject var locationManager = LocationManager.getInstance
这会导致didUpdateLocations
中的DispatchQueue.main.async
在应用程序启动时运行两次-这是正常行为吗?或者,didUpdateLocations
是否可能只运行一次,但处理多个视图?
1条答案
按热度按时间0yg35tkg1#
locationManager.startUpdatingLocation()
用于获取位置流。locationManager.requestLocation()
获取单个位置。只需交换这两个位置。https://developer.apple.com/documentation/corelocation/cllocationmanager/1620548-requestlocation
但是,由于您似乎正在使用SwiftUI,您也可以考虑
https://developer.apple.com/documentation/corelocationui/locationbutton