Search code examples
iosswiftseguecore-location

Passing CLLocation to the next view using segue


I get the current location in the main view, and want to pass this location object to the next view using segue. The segue might be a normal "Show" type of new view page, or an "Embed" type of subview. Here is my script:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var clmanager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        clmanager = CLLocationManager()
        clmanager.delegate = self
        clmanager.requestWhenInUseAuthorization()
        clmanager.startUpdatingLocation()
    }

    var location : CLLocation?
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        location = locations[0]
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "showSegue") { // This part is totally OK
            let dest = segue.destination as! ShowViewController
            dest.object = self.location
        }

        if (segue.identifier == "embedSegue") { // This part is not OK!!!
            let dest = segue.destination as! EmbedViewController
            dest.object = self.location
        }
    }
}

I think the difference between the "Show" and "Embed" type is that the "Show" type is manually activated by users, but the "Embed" type is immediately activated when the main view is loaded. At that time, the location is not still available yet.

How to make the "Embed" part successful? I wish if the updated location is available, the embedded subview should be updated automatically.


Solution

  • add this in your detailViewController

    var location : CLLocation?
    

    //Declare a location variable in first class..

     var location : CLLocation?
        // Get location
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
           // Ammendment here
            location = locations[0]
    
        print(location)
    }
    
    // Pass to the next view
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "thisSegue") {
            let dest = segue.destination as! DetailViewController
            dest.location = self.location
        }
    }
    

    you need to make sure that show perform segue when there is a location available in didUpdateLocations Method