swift - 添加坐标(从 UIViewController)到常量文件

标签 swift api url

我像这样在主视图 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/

相关文章:

python - 获取 strava v3 api python 的请求事件

java - 我可以从哪些地方了解更多有关 API 的信息?

javascript - 在 Reddit 上发布具有相同根 URL 但具有重要片段标识符的文章

python - 在 Flask 中获取位置 header 以返回 id

android - 如何将位于第三方应用程序或浏览器(如 whatsapp 消息)的 url 直接打开到我的 webview 应用程序中?

ios - 关闭模态视图但保留数据

json - swift三层嵌入json数据

ios - 从平移手势中剪切对角线移动

rest - PayPal 智能支付按钮与服务器端 REST API 的集成

javascript - 如何计算欧氏距离? (华硕)