我正在从移动应用程序调用HERE Weather API,需要将当前天气作为对象返回,以便其他方法可以在给定时间段内使用该信息(例如30分钟更新间隔)。
我对基于此站点https://fluffy.es/return-value-from-a-closure/的异步调用有一个粗略的了解,但是我仍然遇到无法访问在completionHandler闭包之外创建的Weather对象的问题。
我从Weather类中提供了Get方法。我还在AppDelegates文件中提供了对该Get方法的调用。
public static func Get(lat:String, long:String, completionHandler: @escaping (Weather?) -> Void) {
//Keys go here
var request = URLRequest(
url: URL(string: "https://weather.cit.api.here.com/weather/1.0/report.json?app_code=-fJW5To2WdHdwQyYr_9ExQ&app_id=2m83HBDDcwAqTC2TqdLR&product=observation&latitude="+lat+"&longitude="+long+"&oneobservation=true")!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request, completionHandler: { dat, response, error in
do {
guard let json = try? JSONSerialization.jsonObject(with: dat as! Data, options: []) else {throw JSONParseError.missingJSON}
//parse json for dictionaries
guard let response = json as? [String: Any] else {throw JSONParseError.responseNotADictionary}
guard let observations = response["observations"] as? [String: Any] else {throw JSONParseError.observationsNotADictionary}
guard let locationJSON = observations["location"] as? [Any] else {throw JSONParseError.locationNotAnArray}
guard let location = locationJSON.first as? [String: Any] else {throw JSONParseError.locationNotADictionary}
guard let observationJSON = location["observation"] as? [Any] else {throw JSONParseError.observationNotAnArray}
guard let observation = observationJSON.first as? [String: Any] else {throw JSONParseError.observationNotADictionary}
//search dictionaries for values
guard let feedCreation = response["feedCreation"] as? String else {throw JSONParseError.missingFeedCreationObject}
guard let city = location["city"] as? String else {throw JSONParseError.missingCityObject}
guard let state = location["state"] as? String else {throw JSONParseError.missingStateObject}
guard let temperature = observation["temperature"] as? String else {throw JSONParseError.missingTemperatureObject}
guard let icon = observation["icon"] as? String else {throw JSONParseError.missingIconObject}
guard let iconName = observation["iconName"] as? String else {throw JSONParseError.missingIconNameObject}
//create weather object and return
guard let currentWeather = Weather(feedCreation: feedCreation,state: state,city: city,temperature: temperature,icon: icon,iconName: iconName) else {throw WeatherObjectCreationError.objectCreationFailed}
completionHandler(currentWeather)
} catch {
print("JSON Serialization error")
}
}).resume()
}
Weather.Get(lat:"32.9005", long:"-96.7869", completionHandler: {currentWeather in
if let testWeather = currentWeather{
//Works fine
print(testWeather.city)
print("completionHandler")
}
})
//Error says testWeather is not intialized
print(testWeather.city)
在Weather.Get调用结束时,我应该能够通过其他方法访问testWeather对象。具体来说,一种方法是根据Weather.Get调用返回的当前区域天气来修改速度限制。
答案 0 :(得分:1)
您还不了解的是,GET调用中的完成处理程序与原始Weather API调用一样异步。因此,您不能在之后中运行任何依赖于 中内容的代码。事件的顺序如下:
// 1
Weather.Get(lat:"32.9005", long:"-96.7869", completionHandler: {currentWeather in
if let testWeather = currentWeather{ // 3!!!
print(testWeather.city) // 4!!!!!!
print("completionHandler")
}
})
print(testWeather.city) // 2
此外,最后一行中的testWeather
是什么? self.testWeather
是财产吗?一定会的。但是,即使是这样,您也忽略了为self.testWeather
赋值; if let testWeather
是一个不同 testWeather
(它仅对完成处理程序而言是本地的,不能从中“泄漏”)。但是,即使您这样做了,它 still 也不起作用,因为代码 still 会以错误的顺序运行:
// 1
Weather.Get(lat:"32.9005", long:"-96.7869", completionHandler: {currentWeather in
if let testWeather = currentWeather{ // 3
print(testWeather.city) // 4
print("completionHandler")
self.testWeather = testWeather // 5; better but it won't help the _next_ print
}
})
print(testWeather.city) // 2
尽管如此,记住记住写self.testWeather
(5)将至少允许 other 代码访问此值,前提是该值运行以后。