尝试从 UIViewController 到天气的序列数据 API
Trying seque data from UIViewController to 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!
}
}
}
现在我要做的是用天气数据更新这个屏幕。下面是我更新天气数据的代码。
所以基本上将从视图控制器选择的城市转移到 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 位于单独的 class 中。所以我正在尝试将 MVC 添加到应用程序中。
我似乎看不出我错过了什么。这可能真的很简单。任何帮助将不胜感激。
您必须调用方法来加载 viewDidLoad
中的数据
override func viewDidLoad() {
super.viewDidLoad()
cityLabel.text = city
userEnteredNewCityName(city: city)
}
并删除行
userEnteredNewCityName(city: city)
在 updateWeatherData
否则你会 运行 进入无限循环
我正在尝试将数据从 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!
}
}
}
现在我要做的是用天气数据更新这个屏幕。下面是我更新天气数据的代码。 所以基本上将从视图控制器选择的城市转移到 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 位于单独的 class 中。所以我正在尝试将 MVC 添加到应用程序中。 我似乎看不出我错过了什么。这可能真的很简单。任何帮助将不胜感激。
您必须调用方法来加载 viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
cityLabel.text = city
userEnteredNewCityName(city: city)
}
并删除行
userEnteredNewCityName(city: city)
在 updateWeatherData
否则你会 运行 进入无限循环