我在将纬度和经度传递给一个函数时遇到问题,我正在构建 api url 以获取一些天气数据。我知道在调用天气函数之前我缺少调用位置函数的东西。基本上我的想法是先获取位置并将纬度和经度存储在一些变量中,然后调用我在其中使用这些值的天气函数。
我已经为我的思路提供了评论。
如有任何帮助,我们将不胜感激。谢谢你。
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locManager = CLLocationManager()
// created these to store the latitude and longitude, are they necessary?
var lat : Double!
var long : Double!
// viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Location Manager - I ask for permission and then start updating
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locManager.requestWhenInUseAuthorization()
locManager.startUpdatingLocation()
// Need something here to call the function where I get the lat and long
//
// This is where I get weather data using the api
getCurrentWeatherData()
}
// Latitude and Longitude - I'm getting the lat and long
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue : CLLocationCoordinate2D = manager.location.coordinate
locManager.stopUpdatingLocation()
lat = locValue.latitude
long = locValue.longitude
}
// I'm using this function to build the api url and get weather data.
func getCurrentWeatherData() -> Void {
let baseURL = NSURL(string: "https://api path here/\(apiKey)/")
let forecastURL = NSURL(string: "\(lat),\(long)", relativeToURL: baseURL)
// more code here //
}
最佳答案
与其存储变量并尝试猜测它们何时设置,不如在 locationManager
处理程序中调用该函数:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue : CLLocationCoordinate2D = manager.location.coordinate
locManager.stopUpdatingLocation()
provideWeatherForLocation(locValue)
// or:
provideWeatherForLocation(latitude: locValue.latitude, longitude: locValue.longitude)
}
关于ios - 如何将纬度和经度传递给另一个函数 - swift location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26870135/