传递给新View Controller的API调用数据问题-Swift

问题描述

我正在构建一个快速的应用程序,并遇到一个问题,即我从API调用中获取的数据未传递到视图控制器。我在整个页面上都有uilabels,并且在进行查询后如我所愿,它们不会更新。我正在尝试在视图控制器 ReportViewController上显示来自用户的航空天气数据。

我可以获取数据以填充WxViewController上的标签,但是不明白为什么我不能镜像相同的代码以使其显示在ReportViewController上。我尝试过复制/粘贴并从WxViewController中删除相同的代码,并且在两个地方都添加了它,但是更新标签的唯一地方是WxViewController(testTextLabel)。任何摆脱这种无尽循环的帮助将不胜感激!

WxViewController

//
//  WxViewController.swift
//  AvWx Pro
//
//  Created by Grayson Bertaina on 9/21/20.
//

import UIKit

class WxViewController: UIViewController,UITextFieldDelegate,WeatherManagerDelegate {

    var weatherManager = WeatherManager()
    
    @IBOutlet weak var testTextField: UILabel!
    
    @IBOutlet weak var stationSearch: UITextField!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        weatherManager.delegate = self
        stationSearch.delegate = self
    }

    @IBAction func searchPressed(_ sender: Any) {
        print(stationSearch.text!)
        stationSearch.endEditing(true)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print(stationSearch.text!)
        stationSearch.endEditing(true)
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if let station = stationSearch.text {
            weatherManager.fetchWeather(stationICAO: station)
        }

        stationSearch.text = ""
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if stationSearch.text != "" {
            return true
        } else {
            stationSearch.placeholder = "Type an ICAO"
            return false
        }
    }
    
    func didUpdateWeather(_ weatherManager: WeatherManager,weather: WeatherModel) {
        DispatchQueue.main.async {
            self.testTextField.text = weather.flightConditions
        }
        print(weather.flightConditions)
        
        
        }
        
    
    
    func didFailWithError(error: Error) {
        print(error)
    }
    
    
    override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    
    
}

ReportViewController

//
//  ReportViewController.swift
//  AvWx Pro
//
//  Created by Grayson Bertaina on 9/22/20.
//

import UIKit

class ReportViewController: UIViewController,WeatherManagerDelegate {

    var weatherManager = WeatherManager()
    
    @IBOutlet weak var flightRulesTitleLabel: UILabel!
    
    @IBOutlet weak var flightRulesValueLabel: UILabel!
    
    @IBOutlet weak var visibilityValueLabel: UILabel!
    
    @IBOutlet weak var altimeterValueLabel: UILabel!
    
    @IBOutlet weak var cloudsTitleLabel: UILabel!
    
    @IBOutlet weak var cloudsType1Label: UILabel!
    
    @IBOutlet weak var cloudsAltitude1Label: UILabel!
    
    @IBOutlet weak var cloudsType2Label: UILabel!
    
    @IBOutlet weak var cloudsAltitude2Label: UILabel!
    
    @IBOutlet weak var cloudsType3Label: UILabel!
    
    @IBOutlet weak var cloudsAltitude3Label: UILabel!
    
    @IBOutlet weak var windGTextLabel: UILabel!
    
    @IBOutlet weak var windSpeedValueLabel: UILabel!
    
    @IBOutlet weak var windGustValueLabel: UILabel!
    
    @IBOutlet weak var windFromTextLabel: UILabel!
    
    @IBOutlet weak var windDirectionValueLabel: UILabel!
    
    @IBOutlet weak var remarksValueLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        weatherManager.delegate = self
        
    }
    

    func didUpdateWeather(_ weatherManager: WeatherManager,weather: WeatherModel) {
        
        DispatchQueue.main.async {
            self.flightRulesValueLabel.text = weather.flightConditions
            print(weather.flightConditions)
        }
        
        
    }
    
    func didFailWithError(error: Error) {
        print(error)
    }
    // In a storyboard-based application,you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    

}

WeatherManager

//
//  WeatherManager.swift
//  AvWx Pro
//
//  Created by Grayson Bertaina on 9/21/20.
//

import Foundation

protocol WeatherManagerDelegate : class {
    func didUpdateWeather(_ weatherManager: WeatherManager,weather: WeatherModel)
    func didFailWithError(error: Error)
}

struct WeatherManager {
    let weatherURL = "https://avwx.rest/api/metar/"
    
    weak var delegate : WeatherManagerDelegate?

    func fetchWeather (stationICAO: String) {
        let urlString = "\(weatherURL)\(stationICAO)?token=OVi45FiTDo1LmyodShfOfoizNe5m9wyuO6Mkc95AN-c"
        performRequest(with: urlString)
    }
    
    func performRequest (with urlString: String) {
        if let url = URL(string: urlString) {
            let session = URLSession(configuration: .default)
                
            
            let task = session.dataTask(with: url) { (data,response,error) in
                if error != nil {
                    self.delegate?.didFailWithError(error: error!)
                    return
                }
                
                if let safeData = data {
                    if let weather = self.parseJSON(safeData) {
                        self.delegate?.didUpdateWeather(self,weather: weather)
                    }
                }
            }
            
            task.resume()
            print(urlString)
            
            
            }
        }
    
    func parseJSON(_ weatherData: Data) -> WeatherModel? {
        
        
        do {
            let decoder = JSONDecoder()
            let decodedData = try decoder.decode(WeatherData.self,from: weatherData)
            
            
            
            let clouds = decodedData.clouds
            let lowCloudsType = (clouds.count > 0 ? clouds[0]?.type : nil) ?? "N/A"
            let midCloudsType = (clouds.count > 1 ? clouds[1]?.type : nil) ?? "N/A"
            let highCloudsType = (clouds.count > 2 ? clouds[2]?.type : nil) ?? "N/A"
            let lowCloudsAlt = (clouds.count > 0 ? clouds[0]?.altitude : nil) ?? 0
            let midCloudsAlt = (clouds.count > 1 ? clouds[1]?.altitude : nil) ?? 0
            let highCloudsAlt = (clouds.count > 2 ? clouds[2]?.altitude : nil) ?? 0
            let reportingStationVar = decodedData.station ?? "N/A"
            let windGustValue = decodedData.wind_gust?.value ?? 0
            let windSpeedValue = decodedData.wind_speed?.value ?? 0
            let windDirectionValue = decodedData.wind_direction?.value ?? 999
            let visibilityValue = decodedData.visibility?.value ?? 0
            let flightRulesValue = decodedData.flight_rules ?? "N/A"
            
            let weather = WeatherModel(lowestCloudsType: lowCloudsType,lowestCloudsAlt: lowCloudsAlt,middleCloudsType: midCloudsType,middleCloudsAlt: midCloudsAlt,highestCloudsType: highCloudsType,highestCloudsAlt: highCloudsAlt,reportingStation: reportingStationVar,windGust: windGustValue,windSpeed: windSpeedValue,windDirection: windDirectionValue,visibility: visibilityValue,flightRules: flightRulesValue)
            
            delegate?.didUpdateWeather(self,weather: weather)
            
            return weather
            
        } catch {
            delegate?.didFailWithError(error: error)
            return nil
        }
    }

}

WeatherData

//
//  WeatherData.swift
//  AvWx Pro
//
//  Created by Grayson Bertaina on 9/21/20.
//

import Foundation

struct WeatherData: Codable {
   
    
    let clouds: [Clouds?]
    let flight_rules: String?
    let remarks: String?
    let wind_speed: WindSpeed?
    let wind_gust: WindGust?
    let wind_direction: WindDirection?
    let visibility: Visibility?

    let station: String?
}



struct Clouds: Codable {
    let type: String
    let altitude: Int
}

struct WindSpeed: Codable {
    let value: Int
}

struct WindGust: Codable {
    let value: Int
}

struct WindDirection: Codable {
    let value: Int
}

struct Visibility: Codable {
    let value: Int
}


再次,我非常感谢您的帮助!运行代码时没有错误。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...