该代码适用于以前的 iOS 版本(16 和 17)。最近我将 iPhone 更新到了 iOS 18.0 公共测试版,现在显示路线的代码失败并出现致命错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MKPolygon needsElevationCorrection]: unrecognized selector sent to instance 0x303295cc0' *** First throw call stack: (0x18861f11c 0x18591e698 0x1887247d4 0x1885bc888 0x1885bc1b0 0x191b08f28 0x191b09150 0x1a86bd424 0x1a86be134 0x191a69344 0x1919d68b8 0x1919d4e90 0x1919d5078 0x1919d54b0 0x1919d59a8 0x1919cb31c 0x104655110 0x104497ca9 0x104498309 0x1043e555d 0x1043e9eb9 0x194084689) libc++abi: terminating due to uncaught exception of type NSException
适用于以前版本的代码:
final class MapService: NSObject, MapServiceInterface, ObservableObject {
var mapView = MKMapView()
override init() {
super.init()
mapView.delegate = self
setup()
}
func setRoute(coordinates: [CLLocationCoordinate2D]) async {
let polyline = MKPolygon(coordinates: coordinates, count: coordinates.count)
await mapView.addOverlay(polyline) // fails and terminates app here
let edges = UIEdgeInsets(top: 10.0,
left: 10.0,
bottom: 12.0,
right: 10.0)
await mapView.setVisibleMapRect(
polyline.boundingMapRect,
edgePadding: edges,
animated: true)
}
func mapView(_ mapView: MKMapView,
rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor(.modernBlue300)
renderer.lineWidth = 6
return renderer
}
}
景色:
struct MapView: View {
@StateObject var viewModel = MapViewModel()
var body: some View {
Wrapper(view: viewModel.mapService.mapView)
}
}
我尝试查找有关此致命错误的信息,互联网上的信息不多,这个问题是新的。尝试更改设置路线的线程,并更改代码行的顺序,给一些时间来呈现 MKMapView,然后执行添加折线代码。
我找到问题所在了。而不是使用
// works on iOS 16.2 - 17, but doesn't work on 18.0
let polyline = MKPolygon(coordinates: coordinates, count: coordinates.count)
我试过了
let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
它修复了崩溃问题。
不知何故,在以前的iOS版本上,我使用
MKPolygon
来显示路线就足够了,但从iOS 18.0公测版开始,我必须使用MKPolyline
来显示路线。