如何从后台线程返回天气数据?

时间:2015-12-24 01:20:15

标签: ios multithreading swift grand-central-dispatch

我有一个名为getWeatherData的方法,它从setLabels中检索一些天气信息,这是另一种方法。我知道这是在后台线程上运行的。我想要的四个变量,city1Info,country1Info,summary1Info和temperature1Info都返回nil,那么在发生这种情况之前如何在主线程上返回它们呢?

func getWeatherData(lat: Double, long: Double) -> (city1: String, country1: String, summary1: String, temperature1: String) {

    var city1Info = ""
    var country1Info = ""
    var summary1Info = ""
    var temperature1Info = ""

    let url = NSURL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.placefinder%20where%20text%3D%22\(lat)%2C\(long)%22%20and%20gflags%3D%22R%22)&format=json")

    // Task does not get onto the main thread until weather data has been retrieved. 
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
        dispatch_async(dispatch_get_main_queue(), {
            self.setLabels(data!)
            city1Info = self.setLabels(data!).city
            country1Info = self.setLabels(data!).country
            summary1Info = self.setLabels(data!).summary
            temperature1Info = self.setLabels(data!).temperature

        })
    }

    task.resume()
    return(city1Info, country1Info, summary1Info, temperature1Info)
}

1 个答案:

答案 0 :(得分:1)

与异步检索数据的方式相同,您必须使getWeatherData函数异步。您可以向此函数发送将使用结果调用的块。

func getWeatherData(lat: Double, long: Double, completion: (city1: String, country1: String, summary1: String, temperature1: String) -> Void) {   
    let url = NSURL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.placefinder%20where%20text%3D%22\(lat)%2C\(long)%22%20and%20gflags%3D%22R%22)&format=json")

    // Task does not get onto the main thread until weather data has been retrieved. 
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
        dispatch_async(dispatch_get_main_queue(), {
            //Get information from data
            let city1Info = ...
            let country1Info = ...
            let summary1Info = ...
            let temperature1Info = ...

            completion(city1Info, country1Info, summary1Info, temperature1Info)
        })
    }

    task.resume()
}