[英]Swift : How to save latitude and longitude to use in another swift file
我在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)
}
我还有另一个具有数据库功能的快捷文件,我需要保存纬度和经度以在数据库中使用
如何将经度和纬度存储在变量中以便在locationManager函数外部使用?
在locationManager(_:didUpdateLocations :)实例方法中执行数据库操作。 或var全局模型。
CLLocationCoordinate2D
只是一个包含2个Double的Struct
。
didUpdateLocations
函数的第一行将当前位置提取到局部变量location
:
let location : CLLocationCoordinate2D = manager.location!.coordinate
您可以将其从局部变量更改为实例变量,并且在该函数外部将可见。 我将其设为可选,因此如果从未分配值,则它将为nil。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.