【发布时间】:2022-11-16 23:25:53
【问题描述】:
我正在使用 swift 版本 5.7.1 和 Xcode 14.1 。我正在创建具有用户位置的地图应用程序并且它工作正常..但这是问题所在,它发出警告..如果在主线程上调用此方法,可能会导致 UI 无响应。相反,请考虑等待 -locationManagerDidChangeAuthorization: 回调并首先检查 authorizationStatus。.
在这条线上.. if CLLocationManager.locationServicesEnabled() {
我已经添加到主线程中。但仍然是同样的警告..这是代码..
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
let mapView = MKMapView()
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mapView)
mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
DispatchQueue.main.async {
self.manager.delegate = self
self.manager.desiredAccuracy = kCLLocationAccuracyBest
self.manager.startUpdatingLocation()
self.mapView.delegate = self
self.mapView.mapType = .standard
self.mapView.isZoomEnabled = true
self.mapView.isScrollEnabled = true
self.mapView.showsUserLocation = false
}
}
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation]) {
guard let mylocation = manager.location else { return }
let myCoordinates: CLLocationCoordinate2D = mylocation.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: myCoordinates, span: span)
mapView.setRegion(region, animated: true)
// comment pin object if showsUserLocation = true
let pin = MKPointAnnotation()
pin.coordinate = myCoordinates
pin.title = "You are here"
mapView.addAnnotation(pin)
}
}
这是屏幕截图..
【问题讨论】:
-
我们也明白了。放声大笑,继续前进。我的意思是,来吧,看在上帝的份上,我们在 App Delegate 上收到了警告!这显然是虚假的。
-
您是否考虑过按照错误消息中非常明确的说明去做?
标签: swift mapkit cllocationmanager