gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:22:20 25 4
gpt4 key购买 nike

我有一个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com