我目前正在学习使用 Swift 进行 iOS 开发。我正在制作一个简单的天气应用程序。我有几个按钮可以获取接下来 4 小时的天气。我从 dark sky 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
中的存储值。
例如
let weather = Weather() print(weather.currentTime)
如果能帮我指明正确的方向,那就太棒了!谢谢!
最佳答案
您可以通过创建 Weather
类 Singleton
来实现。使用单例 此对象仅存在一个副本,并且状态由任何其他对象共享和访问。
class Weather {
public static var sharedInstance = Weather()
...
private init() {
}
}
然后像这样获取单例对象
let weather = Weather.sharedInstance // it will give you the same instance of Weather every time you call it.
关于ios - 从 ViewController 调用时如何检索存储在单独类中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343023/