【问题标题】:How to pass latitude and longitude to another function - swift location如何将纬度和经度传递给另一个函数 - 快速定位
【发布时间】:2015-01-08 07:28:16
【问题描述】:

我无法将纬度和经度传递给我正在构建 api url 以获取一些天气数据的函数。我知道在调用天气函数之前我缺少调用位置函数的东西。基本上我的想法是先获取位置并将纬度和经度存储在一些变量中,然后调用我使用这些值的天气函数。

我已经为我的思路提供了 cmets。

任何帮助将不胜感激。谢谢你。

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

}

【问题讨论】:

    标签: ios swift location cllocationmanager


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多