如何将经度和纬度传递给APIURL?

时间:2019-07-17 10:45:14

标签: swift currentlocation

我想将纬度和经度变量传递给“ weatherData”功能(用户的当前位置)。我无法执行此操作。我在哪里犯错了?

    let locationManager = CLLocationManager()
    var latitude : Double?
    var longitude : Double?

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        latitude = location.latitude
        longitude = location.longitude
        locationManager.stopUpdatingLocation()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }

        weatherData()
    }

    func weatherData()  {
        let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=\(latitude)&lon=\(longitude)&units=metric&appid=APIKEY")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in...

//other codes
...
..
.
}
}

1 个答案:

答案 0 :(得分:1)

我会推荐通读this article,以更好地理解功能和语言。

func weatherData(locationVariable: CLLocation)  {

let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=\(locationVariable.coordinate.latitude)&lon=\(locationVariable.coordinate.longitude)&units=metric&appid=APIKEY")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in...

    //other codes
    ...
    ..
    .
}

您想要做的是传递变量,这样您的最终代码将是;

let locationManager = CLLocationManager()
var varLocation = CLLocation()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location: CLLocation = manager.location else { return }
    varLocation = location
    locationManager.stopUpdatingLocation()
}
override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.requestAlwaysAuthorization()
    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }

    weatherData(locationVariable: varLocation)
}

func weatherData(locationVariable: CLLocation)  {
    let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=\(locationVariable.coordinate.latitude)&lon=\(locationVariable.coordinate.longitude)&units=metric&appid=APIKEY")
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        ...
    }
}

我们还将您的变量更改为CLLocation,以帮助您进行常规整理和强制输入。

相关问题