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

时间:2014-11-11 16:53:49

标签: ios swift location cllocationmanager

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

}

1 个答案:

答案 0 :(得分:2)

您应该只在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)
}