繁体   English   中英

用 swift 中的 JSON 数据填充选择器视图的最佳方法是什么?

[英]what is the best way to populate a picker view with JSON data in swift?

我正在 IOS 上构建 COVID-19 应用程序跟踪器。

为了按国家/地区显示数据,我构建了一个包含所有国家/地区名称的 pickerView。

感谢 HTTP cal,我设法获得了 JSON 数据,即每个国家/地区的名称。 理想情况下,我希望将每个值 append 到一个数组中,然后将填充pickerView。

那可能吗? 如果是,我会怎么做?

我也对其他方式持开放态度。 这是我的代码:

 @IBOutlet weak var confirmedCasesLabel: UILabel!
 @IBOutlet weak var deathsLabel: UILabel!
 @IBOutlet weak var recoveriesLabel: UILabel!

 //MARK: - Relevant variables
 private let covidUrl: String = "https://corona-api.com/countries"
 var countryArray: [String] = [String]()


 override func viewDidLoad() {
     super.viewDidLoad()

     // Do any additional setup after loading the view.
     countryPickerView.delegate = self
     countryPickerView.dataSource = self

     //
     httpCall()
 }


 /*
 // MARK: - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
 }
 */

 //MARK: - Functions that handles picker view delegates and data source
 func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

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

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

 //MARK: - HTTP CALL - GET COUNTRY DATA
 func httpCall() {
     request(covidUrl, method: .get).responseJSON { (response) in
         if response.result.isSuccess {
             //test just print some data
             let dataJSON: JSON = JSON(response.result.value)
             //print(dataJSON)
             //on va identifier chaque pays + l'ajouter au tableau des pays
//                let countryNameJSON = dataJSON["data"][99]["name"]
//                print(countryNameJSON)
             for country in 0...99 {
                 let countryNameJSON = dataJSON["data"][country]["name"].stringValue
                 print(countryNameJSON)
                 //on ajoute ce nom au tabeleau de pays
                 //self.countryArray.append(countryNameJSON)
             }

         }
     }
 }



}

创建一个符合Decodable协议的结构并添加所需的属性

struct Country: Decodable {
    var name: String?
}
  • 在您的 class 中创建名为countryArrayCountry object 类型数组
  • 执行 HTTP 调用
  • 从服务器获取数据
  • 使用 JSONDecoder 解析并加载到countryArray JSONDecoder
  • 解析后重新加载countryPickerView

请按照下面的示例

class YourClass {

    @IBOutlet weak var countryPickerView: UIPickerView!

    var countryArray = [Country]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        countryPickerView.delegate = self
        countryPickerView.dataSource = self
        httpCall()
    }


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

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

    //MARK: - HTTP CALL - GET COUNTRY DATA
    func httpCall() {
        request(covidUrl, method: .get).responseJSON { (response) in
            if response.result.isSuccess {
                let countryArray = try JSONDecoder().decode([Country].self, from: #yourJsonData#)
                countryPickerView.reloadAllComponents()
            }
        }
    }

}

由于Country object 符合Decodable协议,因此解析将在没有循环的情况下完成,因为Struct与您的 JSON 模式匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM