解析OpenWeather JSON数据(SwiftUI)时出现keyNotFound错误 [英] keyNotFound error when parsing OpenWeather JSON data (SwiftUI)

查看:408
本文介绍了解析OpenWeather JSON数据(SwiftUI)时出现keyNotFound错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用openWeather API来检索名称"对象,并且设法解析json并检索数据,但是对于诸如名称"之类的特定对象,我不断收到此错误:

I need to retrieve the "name" object by using openWeather API, and I manage to parse json and retrieve the data, but for its particular objects such as "name" I constantly receiving this error:

keyNotFound(CodingKeys(stringValue:"name",intValue:nil), Swift.DecodingError.Context(codingPath:[],debugDescription:否 与键CodingKeys相关联的值(stringValue:\"name \",intValue: nil)(\名称\").,底层错误:nil))

keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"name\", intValue: nil) (\"name\").", underlyingError: nil))

需要帮助来解决此问题.谢谢.

Need help to solve this issue. Thanks.

这是我的代码(在3个文件中):

This is my code(in 3 Files):

//----------------------WeatherBrain File------------------------------

import Foundation
import SwiftUI

class ClimaBrain : ObservableObject {
    @Published var textFieldValue = ""
    @Published var urlString = ""
    @Published var weatherURL = "https://api.openweathermap.org/data/2.5/find?APPID=03c40ac21db250c8d1ce3aba0bf32c89&q="


    func performRequest(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{
                    print(error!)
                    return
                }
                if let safeData = data{
                    self.parseJSON(weatherData: safeData)

                }
            }
            task.resume()
        }
    }


    func parseJSON(weatherData : Data){
        let decoder = JSONDecoder()
        do{
            let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
            print("Brain Parse Data: \(decodedData.name)")
        } catch{
            print(error)
        }
    }


    func fetchWeather()  {
        urlString = "\(weatherURL)\(textFieldValue)&units=metric&"
        performRequest(urlString: urlString)
    }


    func endEditing() {
        UIApplication.shared.endEditing()
        self.fetchWeather()
    }

}


//----------------------WeatherData File------------------------------

import Foundation

struct WeatherData: Decodable {
    let name : String
    let main: Main
}


struct Main: Decodable {
    let temp: Double
}


//----------------------ContentView File------------------------------

import Foundation
import SwiftUI

struct ContentView: View {

    @ObservedObject var climaBrain = ClimaBrain()

    var body: some View {
        ZStack{
            Image("light_background")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all)
            VStack{
                HStack{

                    TextField("Search", text: $climaBrain.textFieldValue){
                        self.climaBrain.endEditing()
                        print("Return Key:  \(self.climaBrain.urlString)")
                    }
                    .keyboardType(.default)
                    .font(Font.custom("Halvetica", size: 30))
                    .frame(width: 200, height: 60, alignment: .center)
                    .padding(10)
                    VStack{
                        Button(action: {
                            self.climaBrain.endEditing()
                            print("Icon Button: \(self.climaBrain.urlString)")
                        }) {
                            Image(systemName: "magnifyingglass")
                                .renderingMode(.original)
                                .resizable()
                                .scaledToFit()
                                .frame(width: 50, height: 50, alignment: .center)
                        }
                    }
                }
            }
        }
    }
}

推荐答案

您期望WeatherData对象包含2个字段:namemain.但显然,实际数据不包含name.您需要仔细检查要解析的实际数据并更新您的WeatherData模型.

You are expecting a WeatherData object to contain 2 fields: name and main. But apparently, the actual data doesn't contain name. You need to double check the actual data you're trying to parse and update you WeatherData model.

这篇关于解析OpenWeather JSON数据(SwiftUI)时出现keyNotFound错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆