简体   繁体   English

如何将 Json 数据从一个 class 传递到另一个?

[英]How do I pass Json Data from one class to another?

Can someone tell what could I do?有人能告诉我该怎么办吗?

I have a class named RequestManager where i have the URLSession and inside of it, a constant where I store the Data from the server.我有一个名为 RequestManager 的 class ,其中我有 URLSession ,其中有一个常量,我在其中存储来自服务器的数据。

import Foundation

class RequestManager {

    func fetchWeather(cityName: String,completionHandler: @escaping ([String]) -> Void){

        let weatherURL = "https://api.openweathermap.org/data/2.5/weather?q=\(cityName)&appid=55dbb1b10e9f55181ad910227f1460ae&units=metric"
        let objectURL = URL(string: weatherURL)
        let task = URLSession.shared.dataTask(with: objectURL!, completionHandler: {(data,reponse,error)in
            if error != nil{
                print(error!)
            } else{
                do{
                    let json = try JSONDecoder().decode(CityWeatherInfo.self, from: data!)
                    print(json)
                    let saveData: WeatherModel = WeatherModel(name: json.name, 
                    temp: json.main.temp, feelsLike: json.main.feelsLike,
                    tempMin: json.main.tempMin, tempMax: json.main.tempMax,
                    main: json.weathers[0].main, description: json.weathers[0].main)
                    print(saveData)

                } catch{
                    print("error")
                }
            }
        })
        task.resume()
    }
}

I run the app and get this in console when I ask for the server data:当我询问服务器数据时,我运行该应用程序并在控制台中获取它:

CityWeatherInfo(name: "Paris", main: Evaluación_Autofin_México.Main(temp: 20.3, feelsLike: 18.41,
tempMin: 18.0, tempMax: 21.67), weathers: [Evaluación_Autofin_México.Weather(main: "Clouds",
description: "broken clouds")])

WeatherModel(name: "Paris", temp: 20.3, feelsLike: 18.41,
tempMin: 18.0, tempMax: 21.67, main: "Clouds", description: "Clouds")

I need to paste this info into a "WeatherViewDetailController" labels, but I can't enter to the "let saveData" from RequestManager.我需要将此信息粘贴到“WeatherViewDetailController”标签中,但无法从 RequestManager 输入“let saveData”。


class WeatherDetailViewController: UIViewController {

    var weatherPresenter: WeatherDetailPresenter?
    public var cityName: String?

    let request = RequestManager()

    @IBOutlet weak var closeButton: UIButton!
    @IBOutlet weak var cityImage: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var mainLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var tempLabel: UILabel!
    @IBOutlet weak var feelsLikeLabel: UILabel!
    @IBOutlet weak var tempMinLabel: UILabel!
    @IBOutlet weak var tempMaxLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        weatherPresenter = WeatherDetailPresenter(view: self)
        weatherPresenter?.retriveWeatherByCity(cityName: self.cityName ?? "")
        self.view.backgroundColor = UIColor(red: 56/255.0, green: 110/255.0, blue: 185/255.0, alpha: 1.0)
        self.closeButton.tintColor = UIColor(red: 0/255.0, green: 20/255.0, blue: 20/255.0, alpha: 1)

    }

    @IBAction func closeAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
}
extension WeatherDetailViewController: WeatherDetailView {
    func showWeatherSuccessful() {
        print("Success")
    }

    func showWeatherFailure() {
        print("Failure")
    }
}

Update your fetch data with completion完成后更新您的获取数据

func fetchWeather(cityName: String,completionHandler: @escaping (WeatherModel?) -> Void){

        let weatherURL = "https://api.openweathermap.org/data/2.5/weather?q=\(cityName)&appid=55dbb1b10e9f55181ad910227f1460ae&units=metric"
        let objectURL = URL(string: weatherURL)
        let task = URLSession.shared.dataTask(with: objectURL!, completionHandler: {(data,reponse,error)in
            if error != nil{
                print(error!)
            } else{
                do{
                    let json = try JSONDecoder().decode(CityWeatherInfo.self, from: data!)
                    print(json)
                    let saveData: WeatherModel = WeatherModel(name: json.name,
                    temp: json.main.temp, feelsLike: json.main.feelsLike,
                    tempMin: json.main.tempMin, tempMax: json.main.tempMax,
                    main: json.weathers[0].main, description: json.weathers[0].main)
                    print(saveData)

                    completionHandler(saveData)

                } catch{
                    completionHandler(nil)
                    print("error")
                }
            }
        })
        task.resume()
    }

How to use如何使用

class WeatherDetailViewController: UIViewController {

    var weatherPresenter: WeatherDetailPresenter?
    public var cityName: String?

    let request = RequestManager()

 override func viewDidLoad() {
        super.viewDidLoad()
      request.fetchWeather(cityName: "", completionHandler: { [weak self] weatherModel in
                // here you get object and you can set labels

                self?.tempMinLabel.text =  weatherModel.tempMin
                self?. tempMaxLabel.text =  weatherModel.tempMax
               //....
            })
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM