ios - 如何将纬度和经度传递给另一个函数 - swift location

标签 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 //

}

最佳答案

与其存储变量并尝试猜测它们何时设置,不如在 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/

相关文章:

ios - TableView 不重新加载数据

ios - 我想在几个不同的 ViewController 上设置几个不同的 Scrollview

swift - iOS9:UITextField 不允许复制/粘贴

iphone - 如何计算两地之间的距离? iPhone 版 Google map 有可用的服务吗?

ios - CGRectMake坐标指的是哪个坐标

ios - 使用带有 XPATH 的 GDataXML 进行解析

ios - 如何在 Swift 中将 JSON 数组解析为数组

iOS:我的问题是与其他人询问的终止模式下的背景位置跟踪有什么不同

angular - 无法解析 LocationTracker 的所有参数

ios - 如何在 iOS 的全局变量中附加值?