我目前正在使用Swift學習iOS開發。我正在做一個簡單的天氣應用程序。我有幾個按鈕來獲得未來4小時的天氣。我從黑暗的天空API獲取天氣,以JSON格式返回。我終於想出瞭如何從JSON中檢索正確的數據,並創建了一個提取數據的類。從ViewController調用時,如何檢索存儲在單獨類中的數據?
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
存儲的值。
例如
let weather = Weather() print(weather.currentTime)
在指着我在正確的方向將是真棒任何幫助!謝謝!
首先,你應該用'weatherWith'或'updateCurrentData'方法初始化'Weather',然後才能通過天氣類的實例獲得存儲值。 – Poles