[英]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.