【问题标题】:How can I retrieve data stored in a seperate class when calling from ViewController?从 ViewController 调用时,如何检索存储在单独类中的数据?
【发布时间】: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 方法进行初始化,然后只有通过天气类的实例才能获取存储的值。

标签: ios json swift api


【解决方案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.

【讨论】:

  • 我是否必须在init 中分配我的变量?当变量在函数内部分配时,我该怎么做?
  • 没有。我们用 private 声明 init 以防止创建其他天气对象。
【解决方案2】:

您可以使用委托 pettern 在视图控制器中获取结果。首先创建一个这样的协议:

protocol YourDelegateProtocol {
    func getDataFromServer(data: String)
}

之后,在您的 NetworkManager 类中创建此协议的实例,如下所示:

class NetworkManager {
    var delegate: YourDelegateProtocol?    
}

得到响应后,将响应从那里发送到您的视图控制器:

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()

然后像这样在视图控制器中获取数据

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.
   }
}

【讨论】:

    【解决方案3】:

    您可以在 ViewController 中创建请求 getWeather。此函数使您可以访问 Weather 对象作为完成处理程序 (WeatherCallback = (Weather) -> Void)。

    【讨论】:

      【解决方案4】:

      在这里您可以使用单例设计模式。创建一个单例 Weather 类,每当您收到来自 getWeather 函数的响应时,更新您的 Weather 单例类。当您想要用户响应时,只需从 Weather 类中获取值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-02
        • 1970-01-01
        • 2015-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多