I would like to share the coordinates instance and use it on the DiscoverDetailVc. I had 2 location manager instances on my app, after couple research and reading, find out that the best approach is to create a singleton that each VC will use. I came up with the following code but the issue is that on the DiscoverDetailVC, DiscoverRestaurantTableViewController.shared.coordinates is nil however when I print the coordinates from the DiscoverRestaurantVC, I can see the coordinates value. What am I doing wrong in order to get it right.
Thanks
class DiscoverRestaurantTableViewController: UITableViewController, CLLocationManagerDelegate {
static let shared = DiscoverRestaurantTableViewController()
let locationManager = CLLocationManager()
var coordinates: CLLocationCoordinate2D?
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Default implementation to get the coordinates
coordinates = location.coordinate
}
class DiscoverDetailViewController: UIViewController {
func getDirections (){
let coordinate = DiscoverRestaurantTableViewController.shared.coordinates
guard let location = coordinate.coordinates else {return print("booon")}
}
}
Change coordinates = location.coordinate
to DiscoverRestaurantTableViewController.shared.coordinates = location.coordinate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//coordinates = location.coordinate
DiscoverRestaurantTableViewController.shared.coordinates = location.coordinate
}
But it is good to create new class and manage singleton objects. It doesn’t look good to create singleton within TableViewController
.
Hope this helps.