I'm using a MapView and want to display a static image when the map could not be loaded because the device is offline (or tiles could not be loaded for any other reason).
Actually this works when using the MKMapViewDelegate and implementing mapViewDidFailLoadingMap(_:withError).
In my case the MKMapType is .satelliteFlyover and this somehow prevents the delegate method to be called. It works with .satellite for example.
I've tested this both in Simulator and device by turning off any internet connection. An error is printed to the console
[ResourceLoading] Failed to load key: 34.21.6 t:4 kt:0 type: 4, -1009: NSURLErrorDomain
Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSLocalizedDescription=The Internet connection appears to be offline.
But nothing else happens.
Am I doing something wrong? If not: how can I achieve my goal to detect the error correctly? (I'd prefer not to make an URL request or use connectivity detection)
Here is my sample implementation using SwiftUI and a MKMapView wrapped as UIViewRepresentable. Just turn off any internet connection before you run it.
swift
import SwiftUI
import MapKit
struct ContentView: View {
var body: some View {
RepresentableMapView()
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct RepresentableMapView: UIViewRepresentable {
func makeUIView(context: Context) - MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.mapType = .satelliteFlyover
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
}
func makeCoordinator() - Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: RepresentableMapView
init(_ parent: RepresentableMapView) {
self.parent = parent
}
func mapViewDidFinishRenderingMap(_ mapView: MKMapView, fullyRendered: Bool) {
print("mapViewDidFinishRenderingMap")
}
func mapViewDidFailLoadingMap(_ mapView: MKMapView, withError error: Error) {
print(error)
}
}
}