Swift开发时DispatchQueue.main.async内调用locationManager出现错误如何解决?
问题修复说明
报错根本原因
- 你代码中
let locationManager = CLLocationManager()声明的是位置管理器实例变量,不是无参方法,你在闭包中写self.locationManager()相当于尝试把实例对象当成函数调用,不符合语法规则,因此触发报错。 - 你写的
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])是CLLocationManager的代理回调方法,只能由系统在收到位置更新时自动触发,不能手动直接调用。
正确实现逻辑
你拿到API返回的车辆坐标数据后,不需要调用位置管理器相关方法,直接在主线程刷新地图展示即可,替换fetchAndReloadData方法中DispatchQueue.main.async闭包内的代码即可:
DispatchQueue.main.async { // 安全校验避免数组为空、坐标为空的崩溃 guard let lattitude = self.globalVechicle.first?.Latitude, let longitude = self.globalVechicle.first?.Longitude else { return } let carLocation = CLLocationCoordinate2D(latitude: lattitude, longitude: longitude) let region = MKCoordinateRegion(center: carLocation, latitudinalMeters: self.regionInMeters, longitudinalMeters: self.regionInMeters) self.mapView.setRegion(region, animated: true) // 如需显示车辆标记,可在这里初始化MKPointAnnotation添加到mapView }
补充优化建议
- 原
locationManager(_:didUpdateLocations:)代理方法中的mapView.delegate = self可以移动到viewDidLoad中执行,无需每次位置更新都重复赋值 - 访问车辆数组时优先用
.first代替[0]下标访问,避免数组为空时出现索引越界崩溃
内容的提问来源于stack exchange,提问作者bio smile
相关产品推荐
相关产品推荐

