Swift 如何将Lat和Long的值从函数中取出,以便它们可以在VC中的任何其他地方使用?

Swift 如何将Lat和Long的值从函数中取出,以便它们可以在VC中的任何其他地方使用?,swift,Swift,如何从函数中提取Lat和Long的值?我尝试返回,也尝试将值发送到应用程序委托,以便稍后回调,但没有任何效果。这些值被传递给应用程序委托,但无法调用回它们来自的同一个VC。我是swift新手,因此我确信必须有一种更简单的方法来将它们取出,而我忽略了这一点。只需在didUpdateLocation函数外定义userLocation变量,然后更新didUpdateLocation函数内的值,如下所示: func locationManager(_ manager: CLLocationManager

如何从函数中提取Lat和Long的值?我尝试返回,也尝试将值发送到应用程序委托,以便稍后回调,但没有任何效果。这些值被传递给应用程序委托,但无法调用回它们来自的同一个VC。我是swift新手,因此我确信必须有一种更简单的方法来将它们取出,而我忽略了这一点。

只需在
didUpdateLocation
函数外定义
userLocation
变量,然后更新
didUpdateLocation
函数内的值,如下所示:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation = locations.last
    let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

    let camera = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude,
                                          longitude: userLocation!.coordinate.longitude, zoom: 13.0)
    mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    self.view = mapView

    locationManager.stopUpdatingLocation()

    let Lat = "\(userLocation!.coordinate.latitude)"
    let Long = "\(userLocation!.coordinate.longitude)"

}

您可以在my
getUpdatedLocation()之类的任何地方找到lat&long
function.

将它们保存在vc作用域中的变量中如何?您在didUpdateLocations委托方法中获得了lat和long吗?@Joakim我想我已经尝试过了,并一直获得空白值。@BrijeshShiroya我得到了字符串值,但只需要将它们从function@Abe使用单例或保存为用户默认值..但单例可以。请参阅func getUpdatedLocation(){let Lat=“(userLocation!.coordinate.latitude)”let Long=“(userLocation!.coordinate.longitude)”}使用此方法时,值显示为nil首次更新时,位置可能为nil,但是当gps启动时,您将有更新,这些更新将为您提供locationlocationManager。StopUpdateingLocation()为什么要在代码中使用这一行@请转到此链接并对swift 3进行更改
var userLocation: CLLocation?

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    userLocation = locations.last
    let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

    let camera = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude,
                                          longitude: userLocation!.coordinate.longitude, zoom: 13.0)
    mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    self.view = mapView
    locationManager.stopUpdatingLocation()
}

func getUpdatedLocation() {
    let Lat = "\(userLocation!.coordinate.latitude)"
    let Long = "\(userLocation!.coordinate.longitude)"
}