我正在为iOS开发一个天气应用程序,并且尝试从主ViewController调用一个变量,以便在第二个ViewController中使用它,我正在使用OpenWeatherMap的API数据来显示天气数据,这在主ViewController,我希望它显示在第二个“高级详细信息”部分中,该部分将显示最高/最低温度和气压等信息(人们不在乎的事情)。
我已经创建了一个主ViewController的实例'var myCustomViewController:ViewController = ViewController(nibName:nil,bundle:nil)',它可以正常工作,并且我可以从Main Viewcontroller调用标签,变量,TextBoxes等,但我无法调用变量“ weatherData”,这是我的JSON数据的解码器。
在我的第二个View Controller中,我想说'if let gmain =(myCustomViewController.weatherData.main.tempmax'),以获取最高温度,但它不能识别'weatherData'。我非常困惑对此表示感谢,谢谢。
下面的主ViewController中的结构:
struct Coordinate : Decodable {
let lat, lon : Double?
}
struct Weather : Decodable {
var id : Int?
var main, myDescription, icon : String?
enum CodingKeys : String, CodingKey {
case id = "id"
case main = "main"
case icon = "icon"
case myDescription = "description"
}
}
struct Sys : Decodable {
let type, id : Int?
let sunrise, sunset : Date?
let message : Double?
let country : String?
}
struct Main : Decodable {
let temp, tempMin, tempMax : Double?
let pressure, humidity : Int?
}
struct Wind : Decodable {
let speed : Double?
let deg : Int?
}
struct MyWeather : Decodable {
let coord : Coordinate?
let cod, visibility, id : Int?
let name : String?
let base : String?
let weather : [Weather]?
let sys : Sys?
let main : Main?
let wind : Wind?
let dt : Date?
}
下面的主要ViewController代码:
let text: String = userValue.text!
guard let APIUrl = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=" + text + "&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric") else { return }
//API KEY
URLSession.shared.dataTask(with: APIUrl) { data, response, error in
guard let data = data else { return }
let decoder = JSONDecoder()
//Decoder
do {
let weatherData = try decoder.decode(MyWeather.self, from: data)
if (self.MainLabel != nil)
{
if let gmain = (weatherData.weather?.first?.main) { //using .first because Weather is stored in an array
print(gmain)
DispatchQueue.main.async {
self.MainLabel.text! = String (gmain)
}
}
}
if (self.LocationLabel != nil)
{
if let gmain = weatherData.name {
print(gmain)
DispatchQueue.main.async {
self.LocationLabel.text! = "Current Weather in: " + String (gmain)
}
}
}
下面的第二个ViewController代码:
var myCustomViewController: ViewController = ViewController (nibName: nil, bundle: nil) //Inheriting from other viewController
if (self.descriptionLabel != nil)
{
if let gmain = (myCustomViewController.weatherData { //NOT RECOGNISING weatherData <<<<<
print(gmain)
DispatchQueue.main.async {
self.descriptionLabel.text! = String (gmain)
}
}
}
}
答案 0 :(得分:0)
在MainViewController代码中,有以下行:
let weatherData = try decoder.decode(MyWeather.self, from: data)
这是在viewDidLoad
之类的方法内部吗?如果是这样,则weatherData
不是MainViewController的属性,并且不能由子类访问。您必须将其定义为任何函数范围之外的属性(例如,在文件顶部,右括号之后):
var weatherData = ...
然后这样称呼它:
do {
weatherData = ...