Reputation: 1189
I am prompting the user to input latitude and longitudinal coordinates from another view controller. I am not sure how to translate these coordinates to a map, where a pin can be dropped. Below is a setup of my storyboard.
Should I be using UserDefaults to transfer the saved coordinates or a global variable? I am not sure what is the best way to approach this.
Upvotes: 0
Views: 727
Reputation: 93191
You pass the parameter from the first view controller to the second view controller by setting one of its properties.
Here's a step-by-step guide:
1 - In your FirstViewController
, implement the UITabBarControllerDelegate
protocol
class FirstViewController: UIViewController, UITabBarControllerDelegate {
@IBOutlet weak var latitudeField: UITextField!
@IBOutlet weak var longtitudeField: UITextField!
var coordinates = [CLLocationCoordinate2D]()
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
}
@IBAction func addCoordinates(_ sender: Any) {
guard let lat = Double(latitudeField.text!), let long = Double(longtitudeField.text!) else {
return
}
self.coordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: long))
}
// This method will be called whenever you are switching tab
// Note that the viewController can be the same view controller, i.e. FirstViewController
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
guard let secondViewController = viewController as? SecondViewController else {
return
}
secondViewController.coordinates = self.coordinates
}
}
2 - In your SecondViewController
display a pin for the coordinate:
class SecondViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var coordinates = [CLLocationCoordinate2D]() {
didSet {
// Update the pins
// Since it doesn't check for which coordinates are new, it you go back to
// the first view controller and add more coordinates, the old coordinates
// will get a duplicate set of pins
for (index, coordinate) in self.coordinates.enumerated() {
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "Location \(index)"
mapView.addAnnotation(annotation)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "pinAnnotation"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
}
annotationView?.annotation = annotation
return annotationView
}
}
Upvotes: 1