George B George B - 1 year ago 52
iOS Question

Why doesn't my MKMapPointAnnonation appear when the view loads?

In my app, the user saves some data, including a map coordinate. In my code, a pin is dropped at the saved map coordinate. Here is my code-

override func viewDidLoad() {

self.mapView.delegate = self

// Data loading
itemNameTextField.delegate = self
itemDescriptionLabel.delegate = self
itemLocationTextView.delegate = self

// Press recognizer

if let item = item {

itemNameTextField.text = item.itemName
itemDescriptionLabel.text = item.itemDescription
itemLocationTextView.text = item.itemPlace

let dropPin = MKPointAnnotation()
dropPin.coordinate = mapView.convert(item.mapPoint, toCoordinateFrom: mapView)
dropPin.title = "Location of \(item.itemName)"
print("Set the location of item pin to \(String(describing: dropPin.coordinate))")


// Styles
itemInfoView.layer.cornerRadius = 3
itemInfoView.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha: 1.0).cgColor
itemInfoView.layer.shadowOffset = CGSize(width: 0, height: 1.75)
itemInfoView.layer.shadowRadius = 1.7
itemInfoView.layer.shadowOpacity = 0.45

itemLocationView.layer.cornerRadius = 3
itemLocationView.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha: 1.0).cgColor
itemLocationView.layer.shadowOffset = CGSize(width: 0, height: 1.75)
itemLocationView.layer.shadowRadius = 1.7
itemLocationView.layer.shadowOpacity = 0.45

locationAdressTextview.layer.cornerRadius = 2
locationAdressTextview.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha: 1.0).cgColor
locationAdressTextview.layer.shadowOffset = CGSize(width: 0, height: 1.50)
locationAdressTextview.layer.shadowRadius = 1.6
locationAdressTextview.layer.shadowOpacity = 0.3

I know that the app does save the pin coordinates as a CGPoint, and I know that it converts it from a CGPoint to a CLLocationCoordinate2D, because of the
statements I placed. However, when the screen loads, the print statement shows a valid coordinate, but there is no pin on the map, and I get no errors. Can somebody please help me? Thanks!

Answer Source

Whenever the map should display an annotation the MKMapViewDelegate method viewForAnnotation is called so you have to implement that method and return a view according to your needs

Sample code:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotationView")
    // configure the view

    return annotationView
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download