我像这样在主视图 Controller 中从用户那里提取坐标:
import CoreLocation
private let locationManager = CLLocationManager()
func findCurrentLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
然后我将这个 URL 放在一个单独的文件中(我的常量文件)
let NEAREST_CITY_URL = BASE_URL + "nearest_city?lat={{LATITUDE}}&lon={{LONGITUDE}}&key=" + API_KEY
我需要从 View Controller 获取纬度和经度到该 URL。我怎么会把它传到那里?
我假设它需要看起来像这样,但我不知道如何正确编译它。
let NEAREST_CITY_URL = BASE_URL + "nearest_city?lat=\(MainVC.locationManager.locValue.latitude)&lon=\(MainVC.locationManager.locValue.longitude)&key=" + API_KEY
最佳答案
MainVC 需要将数据设置到您的常量文件中,作为一个全局变量(因为您似乎希望使用全局变量......哎呀)。然后您可以提供一个 NEAREST_CITY_URL,它使用该数据计算一个字符串。
在你的常量文件中:
var userLoc : CLLocationCoordinate2D?
let NEAREST_CITY_URL = BASE_URL + "nearest_city?lat=\(userLoc.latitude ?? 0.0)&lon=\(userLoc.longitude ?? 0.0)&key=" + API_KEY
在你的 View Controller 中:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
userLoc = locValue
}
现在像您这样拥有全局常量文件真的很糟糕...至少,将所有常量放入一个名为 Constants 的单例类中。但我只是来直接回答你的问题,所以...
关于swift - 添加坐标(从 UIViewController)到常量文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236342/