-1

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")}

  }
}
Vangola
  • 128
  • 7
  • when did you call` locationManager?` Im guessing when you call vc.shared.coordinates the location manager hasn't been updated yet and when you call it from the DiscoverRestaurantVC the coordinates have been updated – Joshua Aug 22 '19 at 02:34
  • 2
    Don't make a view controller become singleton. Move `locationManager`, `coordinates`, `CLLocationManagerDelegate` to another object and make it singleton. After that you can use singleton object inside both 2 view controllers. – trungduc Aug 22 '19 at 02:36
  • I am able to see the coordinates value when I print it on the console before using vc.shared.coordinates. – Vangola Aug 22 '19 at 02:37
  • 100% concur with @trungduc. Here's how you do a singleton: https://krakendev.io/blog/the-right-way-to-write-a-singleton – Adrian Aug 22 '19 at 02:48

1 Answers1

2

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.

Santosh
  • 363
  • 2
  • 14