【发布时间】:2016-12-27 10:03:07
【问题描述】:
我目前正在学习使用 Swift 进行 iOS 开发。我正在制作一个简单的天气应用程序。我有几个按钮可以获取接下来 4 小时的天气。我从黑暗天空 API 获取天气,以 JSON 格式返回。我终于弄清楚了如何从 JSON 中检索正确的数据,并创建了一个获取数据的类。
typealias WeatherCallback = (Weather) -> Void
typealias ErrorCallback = (Error) -> Void
class NetworkManager {
class func getWeather(latitude: String, longitude: String, onSuccess: WeatherCallback? = nil, onError: ErrorCallback? = nil) {
let urlString = "https://api.darksky.net/forecast/(api key)/" + latitude + "," + longitude + "?units=si"
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error!)
onError?(error!)
} else {
do {
let json = JSON(data: data!)
let weather = Weather()
DispatchQueue.main.async {
weather.updateWithJSON(dict: json["currently"], hour: 0)
for i in 1...4 {
weather.updateWithJSON(dict: json["hourly"]["data"][i], hour: i)
}
}
onSuccess?(weather)
}
}
}.resume()
}
}
我有一个不同的类来存储检索到的数据。
class Weather {
public var currentTime: String = ""
public var currentTemperature: String = ""
public var nextHourTime: String = ""
public var nextHourTemperature: String = ""
public var nextTwoHourTime: String = ""
public var nextTwoHourTemperature: String = ""
public var nextThreeHourTime: String = ""
public var nextThreeHourTemperature: String = ""
public var nextFourHourTime: String = ""
public var nextFourHourTemperature: String = ""
func updateCurrentData(time: String, temp: String) {
currentTime = time
currentTemperature = temp
}
func updateWithJSON(dict: JSON, hour: Int){
switch hour {
case 0:
currentTime = dict["time"].stringValue
currentTemperature = dict["temperature"].stringValue
case 1:
nextHourTime = dict["time"].stringValue
nextHourTemperature = dict["temperature"].stringValue
case 2:
nextTwoHourTime = dict["time"].stringValue
nextTwoHourTemperature = dict["temperature"].stringValue
case 3:
nextThreeHourTime = dict["time"].stringValue
nextThreeHourTemperature = dict["temperature"].stringValue
case 4:
nextFourHourTime = dict["time"].stringValue
nextFourHourTemperature = dict["temperature"].stringValue
default:
print("rip")
}
}
}
我的问题是,我无法从ViewController 中访问Weather 类中的存储值。
例如
让天气 = Weather() 打印(天气.当前时间)
任何能指引我正确方向的帮助都会很棒!谢谢!
【问题讨论】:
-
首先您应该使用
Weather和updateWithJSON或updateCurrentData方法进行初始化,然后只有通过天气类的实例才能获取存储的值。