I am currently learning swift and I want to find the user's current location in one View Controller (ViewController A) and save it. And later on display the saved location in another View Controller (ViewController B). It can locate and find the current location. When printing it, it shows the coordinate as well. But it cannot be passed to another View Controller. I am not sure if it is an appropriate way to save the coordinate (return a value in function). Here is the code that I work with:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> CLLocation {
let currentLocation: CLLocation = locations[0] as CLLocation
let lat = currentLocation.coordinate.latitude
let long = currentLocation.coordinate.longitude
let center = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
let latDelta = 0.05
let longDelta = 0.05
let currentLocationSpan:MKCoordinateSpan =
MKCoordinateSpanMake(latDelta, longDelta)
let region = MKCoordinateRegion(center: center, span: currentLocationSpan)
myMapView.setRegion(region, animated: true)
let myAnnotation: MKPointAnnotation = MKPointAnnotation()
myAnnotation.coordinate = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
myAnnotation.title = "Current Location"
myMapView.addAnnotation(myAnnotation)
print("The latitude is \(lat)")
print("The longitude is\(long)")
print(currentLocation)
return currentLocation
}
And in View Controller B, the code is like that and it does not know what currentLocation is:
class ViewControllerB: ViewControllerA {
override func viewDidLoad() {
super.viewDidLoad()
let center = CLLocationCoordinate2D(latitude:currentLocation.coordinate.latitude, longitude:currentLocation.coordinate.longitude)
}
Does anyone know how to fix it? Millions thanks!