简体   繁体   English

Swift:如何保存经纬度以在另一个Swift文件中使用

[英]Swift : How to save latitude and longitude to use in another swift file

I have this code in ViewController to capture the current location from users: 我在ViewController中有以下代码可以捕获用户的当前位置:

@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? 如何将经度和纬度存储在变量中以便在locationManager函数外部使用?

do database operations in your locationManager(_:didUpdateLocations:) Instance Method. 在locationManager(_:didUpdateLocations :)实例方法中执行数据库操作。 Or var a Global Model. 或var全局模型。

CLLocationCoordinate2D is just a Struct containing 2 Doubles. CLLocationCoordinate2D只是一个包含2个Double的Struct

The very first line of your didUpdateLocations function extracts the current location into a local variable location : didUpdateLocations函数的第一行将当前位置提取到局部变量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. 我将其设为可选,因此如果从未分配值,则它将为nil。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM