gpt4 book ai didi

swift - 如何将经纬度传递给 APIURL?

转载 作者:行者123 更新时间:2023-11-28 13:32:58 25 4
gpt4 key购买 nike

我想将纬度和经度变量传递给“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
...
..
.
}
}

最佳答案

我会推荐通读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 以帮助整体整洁和类型强制。

关于swift - 如何将经纬度传递给 APIURL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57074058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com