![](/img/trans.png)
[英]Pass Json response from one Viewcontroller to another Viewcontroller and populate CollectionView
[英]How to pass a JSON value from one ViewController to another
我正在嘗試將JSON值傳遞給另一個ViewController,在這種情況下,它是用戶希望輸入的任何城市中當前天氣的描述。 我可以在主View Controller(ViewController)上很好地獲取和顯示JSON數據,但是我想讓它顯示在我的第二個View Controller(AdvancedViewController)上,作為高級且更為詳細的部分,等等。試圖通過的是'gmain',正如您在下面的代碼中看到的那樣,它位於按鈕函數內部,並且位於viewDidLoad()外部。
在我的AdvancedViewController代碼中,我已經做到了,因此我可以輸入“ vc”來訪問ViewController的內容。 在從該ViewController輸入變量之前,我可以訪問標簽,文本框,按鈕等,但無法識別'gmain',您可以在代碼底部看到,我正在嘗試將'gmain'的值分配給我AdvancedViewController中的標簽。 如您所見,我的AdvancedViewController中的代碼位於viewDidLoad()中,因為我希望在打開該特定View Controller時將其顯示給用戶。
由於我被完全卡住了,所以我將不勝感激,並且我已經待了幾天。 先感謝您。
我的ViewController中的JSON結構如下:
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中的GoButton函數:
@IBAction func GoButton(_ sender: Any) {
let text: String = userValue.text!
guard let APIUrl = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=" + text + "&appid=***API***KEY***&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)
}
}
}
} catch {
print(error.localizedDescription)
}
}.resume()
AdvancedViewController代碼如下:
class AdvancedViewController: UIViewController {
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let vc = ViewController(nibName: "ViewController", bundle: nil)
Label.text! = String (vc.gmain) //NOT WORKING <<
}
您將要通過segue傳遞數據。 當即將執行segue時,您的第一個視圖控制器將具有名為https://developer.apple.com/documentation/uikit/uiviewcontroller/1621490-prepareforsegue的 prepareForSegue
因此,您需要重寫它並實現代碼以從segue參數讀取destinationViewController
。
例如
// in MainViewController
override func prepare(for segue: UIStoryboardSegue,
sender: Any?) {
let nextVC = segue.destinationViewController as? AdvancedViewController
nextVC?.data = myData
}
另外,我只想給您一個小技巧,以確保您在視圖控制器中的屬性以小寫字母開頭。 所有變量和屬性均以小寫字母開頭,以符合命名約定。 這將有助於稍微區分變量(分配東西的對象)和類型(實例化並分配給變量的實際數據結構)之間的區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.