ios – 如何将纬度和经度传递给另一个函数 – 快速定位

我无法将纬度和经度传递给我正在构建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)
}
点赞