I have this code in ViewController to capture the current location from users:
@IBOutlet weak var userMapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location : CLLocationCoordinate2D = manager.location!.coordinate
print(location.latitude)
let latitudeDelta : CLLocationDegrees = 0.01
let longitudeDelta : CLLocationDegrees = 0.01
let span : MKCoordinateSpan = MKCoordinateSpanMake(latitudeDelta, longitudeDelta)
let center : CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.latitude, location.longitude)
let region : MKCoordinateRegion = MKCoordinateRegionMake(center, span)
self.userMapView.setRegion(region, animated: false)
self.userMapView.removeAnnotations(userMapView.annotations)
let userPinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.latitude, location.longitude)
let pinAnnotation = MKPointAnnotation()
pinAnnotation.coordinate = userPinLocation
pinAnnotation.title = "Sua localização atual"
self.userMapView.addAnnotation(pinAnnotation)
}
I have another swift file with the Database Functions, and I need save the latitude and longitude for use in database
How I store the latitude and longitude in variables to use outside the locationManager function?
do database operations in your locationManager(_:didUpdateLocations:) Instance Method. Or var a Global Model.
CLLocationCoordinate2D
is just a Struct
containing 2 Doubles.
The very first line of your didUpdateLocations
function extracts the current location into a local variable location
:
let location : CLLocationCoordinate2D = manager.location!.coordinate
You could just change that from a local variable to an instance variable and it would be visible outside of that function. I'd make it an optional so it would be nil if the value was never assigned.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.