Reputation: 698
MKMapView
class is added and assigned delegate:
let mapView: MKMapView = {
let map = MKMapView()
map.translatesAutoresizingMaskIntoConstraints = false
return map
}()
override func viewDidLoad() {
self.view.addSubview(mapView)
mapView.delegate = self
let center = mapView.centerCoordinate
NSLayoutConstraint.activate([
mapView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0),
mapView.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 0),
mapView.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor, constant: 0),
mapView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: 0)
])
}
Then the mapView
is assigned center
coordinate and span is set. zoomLevel
is set to 1
let span = MKCoordinateSpan(latitudeDelta: 0, longitudeDelta: 360 / pow(2, Double(zoomLevel)) * Double(mapView.frame.size.width) / 256)
setRegion(MKCoordinateRegion(center: coordinate, span: span), animated: animated)
// I wrote URL like this because I was told that MKTileOverlay
class will take care of z
, x
, and y
value.
let urlTemplate = "https://tile.openweathermap.org/map/temp_new/{z}/{x}/{y}.png?appid={my API ID}"
// urlTemplate
is added to MKTileOverlay
let overlay = MKTileOverlay(urlTemplate: urlTemplate)
overlay.canReplaceMapContent = true
// And just when I am about to add overlay
to mapView
, the app will crash:
self.mapView.addOverlay(overlay)
// It takes me to AppDelegate.swift
and then it shows this message:
Thread 1: Exception: "Expected a MKTileOverlay but got (null)"
Everything was added to viewDidLoad()
.
I also added renderedFor
delegate functions. Like this:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
var renderer = MKTileOverlayRenderer()
print("overlay rendered For: \(overlay)")
if overlay is MKTileOverlay {
renderer = MKTileOverlayRenderer(overlay:overlay)
renderer.alpha = 0.8
}
return renderer
}
Upvotes: 0
Views: 224
Reputation: 29
I had the same problem and what was causing the crash for me was the initialisation of MKTileOverlayRenderer()
without specifying an overlay.
So basically, your code inside the mapView(_:rendererFor:)
delegate method should be:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
print("overlay rendered For: \(overlay)")
if let overlay = overlay as? MKTileOverlay {
renderer = MKTileOverlayRenderer(overlay: overlay)
renderer.alpha = 0.8
return renderer.alpha
} else {
return MKOverlayRenderer(overlay: overlay)
}
}
Upvotes: 0