Nitesh Nitesh - 2 years ago 124
Swift Question

Passing Location to other view controller

I'm getting location on my HomeViewController then I want to pass that to other NextViewController but it always returns nothing.

HomeViewController - Declaration

struct MyVariables {

static var fetchedLat = String()
static var fetchedLong = String()

class HomeViewController: UIViewController,UITableViewDataSource,UITableViewDelegate, CLLocationManagerDelegate, NSFetchedResultsControllerDelegate {

var location: CLLocation!{
lat = "\(location.coordinate.latitude)"
long = "\(location.coordinate.longitude)"

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
MyVariables.fetchedLat = String("\(locValue.latitude)")
MyVariables.fetchedLong = String("\(locValue.longitude)")
print("locations = \(locValue.latitude) \(locValue.longitude)")
location = (locations ).last

override func viewDidLoad() {



if CLLocationManager.locationServicesEnabled()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters

NextViewController - ViewDidLoad

MyVariables.fetchedLat = outputLat
MyVariables.fetchedLong = outputLong

Please let me know if there is any better way so that I can access Lat & Long in all other ViewController in my App.

Answer Source

Define var passedData:CLLocationManger? globally in HomeViewController class

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //let cell = tableView.cellForRowAtIndexPath(indexPath)
        index = indexPath.row

        performSegueWithIdentifier("yourSegue", sender: self)

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)       
        if segue.identifier == "yourSegue"
        let destVC = segue.destinationViewController as! NextViewController 
        destVC.passedData = locationData // both are of Type CLLocationManager


In NextViewController declare this globally in class:-

var locationData:CLLocationManager?

then access in NextViewController as



Note:- Instead of passing latitude and longitude, pass the CLLocationManager itself as you can access all properties of CLLocationManager i.e. Latitude, Longitude, Coordinate etc

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