我使用的是swift版本5.7.1和Xcode 14.1。我正在使用用户位置创建Map应用程序,它工作正常。但问题是,它发出警告。如果在主线程上调用此方法,则可能导致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)
}
}
下面是截图。
2条答案
按热度按时间bkkx9g8r1#
这个警告告诉你不应该调用
CLLocationManager.locationServicesEnabled()
,因为这会花费很长时间并导致UI出现问题。相反,你应该实现委托函数locationManagerDidChangeAuthorization(_:)
,检查authorizationStatus
并将结果存储在某个地方,然后在if
中使用存储的值。jgwigjjp2#
请尝试使用位置管理器更改授权: