Nitesh Nitesh - 4 months ago 17
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!{
didSet{
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
locationManager.stopUpdatingLocation()
}


override func viewDidLoad() {
super.viewDidLoad()

self.locationManager.requestAlwaysAuthorization()

self.locationManager.requestWhenInUseAuthorization()

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


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

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

 locationData.location.coordinate.latitude

 locationData.location.coordinate.longitude

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

Comments