我的视图控制器文件中有一个名为temperature的实例变量,以及一个带有所有cityID的数组
var temperature:Array<String>?
我有一个获取城市温度的函数:
func getCityCurrentTemperture(cityID:String){
let session = URLSession.shared
let weatherURL = URL(string: "http://api.openweathermap.org/data/2.5/weather?id=\(cityID)&APPID=\(apiId)")!
let dataTask = session.dataTask(with: weatherURL) {
(data: Data?, response: URLResponse?, error: Error?) in
if let error = error {
let errorCode=(error as NSError).code
if errorCode == -1009{
print("no internet")
}else{
print("Error:\n\(error)")
}
} else {
if let data = data {
let dataString = String(data: data, encoding: String.Encoding.utf8)
// print("All the weather data:\n\(dataString!)")
if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
if let mainDictionary = jsonObj!.value(forKey: "main") as? NSDictionary {
if let temperture = mainDictionary.value(forKey: "temp") {
DispatchQueue.main.async {
let currTempNumber = (temperture as? Double)! - 273.15
// let currTempText = "\(currTempNumber)°C"
let currTempText=String(format: "%.02f °C", currTempNumber)
self.temperture?.append(currTempText)
}
}
}
} else {
print("Error: unable to convert json data")
}
} else {
print("Error: did not receive data")
}
}
}
dataTask.resume()
}
然后,在 ViewDidLoad()中:
for i in cityID{
getCityCurrentTemperture(cityID: i)
}
print(temperature)
温度始终显示为零。 我是Swift的新手,我不知道如何将数据存储回数组。 在正确存储城市的温度后,我需要使用温度进行进一步的工作。 我怎样才能做到这一点?预先感谢