Swift:如何在另一个swift文件中保存经度和经度

时间:2016-09-11 01:04:44

标签: ios swift maps mkmapview cllocationmanager

我在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)

}

我有另一个带有数据库功能的swift文件,我需要保存在数据库中使用的纬度和经度

如何将纬度和经度存储在变量中以在locationManager函数外部使用?

2 个答案:

答案 0 :(得分:0)

在您的locationManager(_:didUpdateLocations :)实例方法中执行数据库操作。 或者变换全局模型。

答案 1 :(得分:0)

CLLocationCoordinate2D只是一个包含2个双打的Struct

didUpdateLocations函数的第一行将当前位置提取到局部变量location中:

let location : CLLocationCoordinate2D = manager.location!.coordinate

您可以将其从局部变量更改为实例变量,并且它将在该函数之外可见。我将它设为可选项,因此如果从未赋值,则为零。