如果你想getWeather
完成後做一些事情,添加完成處理。就個人而言,我會通過創建一個結構,傳回捕獲的信息簡化這個:
struct WeatherReport {
let latitude: Double
let longitude: Double
let temperature: Double
let name: String
let desc: String
}
func getWeather(city: String, completion: @escaping (WeatherReport?, Error?) -> Void) {
...
let task = session.dataTask(with: url!) { data, _, error in
...
guard successful else {
completion(nil, error)
return
}
let weatherReport = WeatherReport(...)
completion(weatherReport, nil)
}
task.resume()
}
然後
override func viewDidLoad() {
super.viewDidLoad()
getWeather(city: "Minsk") { weatherReport, error in
guard let weatherReport = weatherReport, error == nil else {
print(error?.localizedDescription ?? "Unknown error")
return
}
DispatchQueue.main.async {
// do something with `weatherReport` here
}
}
}
注意,dataTask
已經(一)以異步方式運行;和(b)運行在後臺線程其完成處理程序,因此具有viewDidLoad
明確地調度任何它確實與模型對象和/或在getWeather
完成處理程序的UI到主隊列中,如上所示。
順便說一句,如果你使用斯威夫特4,我建議消除第三方JSON解析庫,並使用JSONDecoder
和模型結構,是Decodable
,如:
struct Coordinate: Decodable {
let latitude: Double
let longitude: Double
enum CodingKeys: String, CodingKey {
case latitude = "lat"
case longitude = "lon"
}
}
struct WeatherReportDetails: Decodable {
let temperature: Double
let pressure: Double
let humidity: Double
let temperatureMin: Double
let temperatureMax: Double
enum CodingKeys: String, CodingKey {
case pressure, humidity
case temperature = "temp"
case temperatureMin = "temp_min"
case temperatureMax = "temp_max"
}
}
struct WeatherReport: Decodable {
let coordinate: Coordinate
let details: WeatherReportDetails
let name: String
enum CodingKeys: String, CodingKey {
case name
case coordinate = "coord"
case details = "main"
}
}
然後
func getWeather(city: String, completion: @escaping (WeatherReport?, Error?) -> Void) {
let cityEscaped = city.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
let urlString = "http://samples.openweathermap.org/data/2.5/weather?q=" + cityEscaped + "&appid=..." // appid removed for privacy’s sake
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data, error == nil else {
completion(nil, error)
return
}
do {
let weatherReport = try JSONDecoder().decode(WeatherReport.self, from: data)
completion(weatherReport, nil)
} catch {
completion(nil, error)
}
}
task.resume()
}
來源
2017-10-17 15:53:08
Rob
翻譯您的問題... –
你想先打印結果,然後下載呢? –
爲「Hello」之後的「緯度經度」帶來的是什麼意思? –