danicode
danicode

Reputation: 25

Problem with callout button and firestore in swift

I have 5 collections on Firestore. With the data of the documents of those collections, I create annotations of different types and display them on a map view.

The problem is that I want to pass all the information that is stored in each annotation and display it on another view controller, that appears when you press the callout button.

I can't figure out a way of referencing the annotation I'm pressing and then pass the data to the other screen.

This is my first time using databases and I don't have many experience, so I would appreciate some help.

Thanks!

Upvotes: 0

Views: 48

Answers (1)

Isuru
Isuru

Reputation: 31283

It's difficult to give a specific answer since I don't know the full scope of your features. But this is how you generally do it.

First when you create the MKAnnotation subclass, you define a property to hold an object that you can reference later. For example, say I'm showing restaurants and supermarkets in a map.

class RestaurantAnnotation: NSObject, MKAnnotation {
    let restaurant: Restaurant
    
    var title: String? {
        return restaurant.name
    }
    
    var coordinate: CLLocationCoordinate2D {
        return restaurant.coordinate
    }
    
    init(restaurant: Restaurant) {
        self.restaurant = restaurant
        super.init()
    }
}

struct Restaurant {
    let name: String
    let coordinate: CLLocationCoordinate2D
}

Same goes for the supermarkets.

Then when you create the annotation, you pass the Restaurant object to it.

let restaurant = Restaurant(name: "McDonald's", coordinate: CLLocationCoordinate2D(latitude: 27.2831, longitude: -127.831))
let restaurantAnnotation = RestaurantAnnotation(restaurant: restaurant)
mapView.addAnnotation(restaurantAnnotation)

You implement the mapView(_:annotationView:calloutAccessoryControlTapped:) delegate method to be notified when the user taps on the callout button in annotations. In it, you can easily reference the object you passed to it earlier.

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if let annotation = view.annotation as? RestaurantAnnotation {
        print(annotation.restaurant)
    } else if let annotation = view.annotation as? SupermarketAnnotation {
        print(annotation.supermarket)
    }
}

And you can use that data to do whatever you want after that. In your case, pass it to a new screen.

Upvotes: 1

Related Questions