我目前正在使用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")
}
}
}
我的问题是,我无法从Weather
内访问班级ViewController
中存储的值。
例如
let weather = Weather() print(weather.currentTime)
任何指导我指向正确方向的帮助都会很棒!谢谢!
答案 0 :(得分:1)
您可以通过创建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.
答案 1 :(得分:1)
您可以使用delegate pettern在viewcontroller中获取结果。首先创建一个类似的协议:
protocol YourDelegateProtocol {
func getDataFromServer(data: String)
}
之后在NetworkManager类中创建此协议的实例,如下所示:
class NetworkManager {
var delegate: YourDelegateProtocol?
}
获得响应后,从那里将响应发送到您的viewcontroller:
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error!)
onError?(error!)
} else {
do {
let json = JSON(data: data!)
delegate.geDataFromServer(json as String)
}
onSuccess?(weather)
}
}
}.resume()
之后获取viewcontroller中的数据
class WeatherData: UIViewController, YourDelegateProtocol {
var yourModelClass = YourModelClass() //init model class globally.
func getDataFromServer(data: String) {
// populate json String into your model class. Then you are ready to go.
}
}
答案 2 :(得分:0)
您可以在ViewController中创建请求getWeather。此功能使您可以访问Weather对象作为完成处理程序(WeatherCallback =(Weather) - > Void)。
答案 3 :(得分:0)
在这里,您可以使用Singleton设计模式。创建一个Singleton Weather
类,每当您从getWeather
函数获得响应时,都会更新您的Weather
单例类。当您想要用户响应时,只需从Weather
类获取值。