尝试从UIViewController到Weather API隔离数据

时间:2019-02-21 15:38:06

标签: ios swift weather-api

我试图将数据从UIViewController传递到从WeatherAPI获取数据的SecondViewController。

 import UIKit

class ViewController: UIViewController {

@IBOutlet weak var raceTextField: UITextField!


let races = ["Melbourne", "Bahrain", "Shanghai", "Baku",
             "Barcelona", "Monaco", "Montreal","Le Castellet","Speilberg",
             "Silverstone","Hockenheimring","Budapest","Spa-Francorchamps","Monza","Singapore","Sochi","Suzuka","Austin","Interlagos","Abu Dhabi"]
var selectedRace: String?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    createRacesPicker()
    createToolbar()
}


@IBAction func sendButtonPressed(_ sender: Any) {
    performSegue(withIdentifier: "getWeather", sender: self)
}

func createRacesPicker() {
    let racePicker = UIPickerView()
    racePicker.delegate = self
    raceTextField.inputView = racePicker
}
func createToolbar() {
    let toolBar = UIToolbar()
    toolBar.sizeToFit()
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.dismissKeyboard))
    toolBar.setItems([doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    raceTextField.inputAccessoryView = toolBar
}
@objc func dismissKeyboard(){
    view.endEditing(true)
}
}
 //MARK: - UIPickerView Delegate extension
 /***************************************************************/
//UIPickerView here
 extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource{
   func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
   }

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: 
Int) -> Int {
    return races.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return races[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    selectedRace = races[row]
    raceTextField.text = selectedRace
}
//Write the PrepareForSegue Method here
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "getWeather" {
        let weatherVC = segue.destination as! WeatherViewController

        weatherVC.city = raceTextField.text!
       }
     }
   }

现在,我要用天气数据更新此屏幕。下面是我的代码来更新weatherData。 因此,基本上可以将从视图控制器选择的城市选择到WeatherViewController

import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON

class WeatherViewController: UIViewController {

//constants
let weatherDataModel = WeatherDataModel()

var city = ""

@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var weatherIcon: UIImageView!
@IBOutlet weak var temperatureLabel: UILabel!

let WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather"
let APP_ID = "8a99df7bf7ef4a4a202732c392b2d240"

override func viewDidLoad() {
    super.viewDidLoad()
    cityLabel.text = city
    // Do any additional setup after loading the view.
}

//MARK: - Networking
/***************************************************************/

//Write the getWeatherData method here:
func getWeatherData(url: String, parameters: [String : String]) {
    Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
        response in
        if response.result.isSuccess {
            print("Success we got the weather data!")
            let weatherJSON : JSON = JSON(response.result.value!)
            self.updateWeatherData(json: weatherJSON)

        } else {
            print("Error \(String(describing: response.result.error))")
            //self because of the closure.  Therefore you have to specify the function.
            self.cityLabel.text = "Connection Issues"
        }

    }
}

//MARK: - JSON Parsing
/***************************************************************/
//updateweatherdata method here

func updateWeatherData(json: JSON) {
    if let tempResult = json["main"]["temp"].double {
        weatherDataModel.temperature = Int(tempResult - 273)
        weatherDataModel.city = json["name"].stringValue
        weatherDataModel.condition = json["weather"][0]["id"].intValue
        weatherDataModel.weatherIconName = weatherDataModel.updateWeathericon(condition: weatherDataModel.condition)
        userEnteredNewCityName(city: city)
        updateUIWithWeatherData()
    } else {
        cityLabel.text = "No data available"
    }

}

func userEnteredNewCityName(city: String){
    let params : [String : String] = ["q" : city, "appid" : APP_ID]
    getWeatherData(url: WEATHER_URL, parameters: params)
}

 //Write the updateUIWithWeatherData method here:


func updateUIWithWeatherData() {
    cityLabel.text = weatherDataModel.city
    temperatureLabel.text = String(weatherDataModel.temperature)
    weatherIcon.image = UIImage()
  }

 }

weatherDataModel在单独的类中。所以我试图将MVC添加到应用程序中。 我似乎看不到我所缺少的东西。这可能真的很简单。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您必须调用方法以将数据加载到viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    cityLabel.text = city
    userEnteredNewCityName(city: city)
}

并删除行

userEnteredNewCityName(city: city)

updateWeatherData中,否则您将陷入无限循环