将坐标(来自UIViewController)添加到常量文件

时间:2018-11-10 05:48:57

标签: swift api url

我像这样在主视图控制器中从用户那里获取坐标:

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

我需要从视图控制器中获取该纬度和经度。我如何将其传递到那里?

我认为它需要看起来像这样,但是我想不出如何正确编译它。

let NEAREST_CITY_URL = BASE_URL + "nearest_city?lat=\(MainVC.locationManager.locValue.latitude)&lon=\(MainVC.locationManager.locValue.longitude)&key=" + API_KEY

1 个答案:

答案 0 :(得分:1)

MainVC需要将数据作为全局变量设置到常量文件中(因为您似乎希望使用globals ... eek)。然后,您可以提供一个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

在您的视图控制器中:

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的单例类中。但是我只是在这里直接回答您的问题,所以...