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

标签 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)
}

最佳答案

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

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()
}

关于ios - 如何从后台线程返回天气数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34446058/

相关文章:

html - 在没有自动全屏的情况下在 iOS 中嵌入 YouTube 视频

c++ - TBB::parallel_for 创建了太多类/正文拷贝?

swift - 以编程方式将渐变边框颜色应用于 UIButton

ios - Swift 5.5 异步让 - 错误 : expression is 'async' but is not marked with 'await'

ios - 在 UIWebView 中从 AVPlayer 获取视频 URL

ios - 弹出到 viewcontroller 编辑文本

ios - NSUserDefaults 不保存完整的对象

ios - 在swift中确定数组是否包含另一个数组的一个或多个元素

c# - 暂停线程直到手动恢复

.net - Visual Studio 的线程窗口如何识别 "Main Thread'