在swift中用JSON数据填充picker视图的最佳方法是什么?

问题描述 投票:1回答:1

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

为了按国家显示数据,我建立了一个pickerView,其中将包含所有国家名称。

理想情况下,我希望将每个值附加到一个数组中,而这个数组又会填充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)
             }

         }
     }
 }



}
json swift xcode api uipickerview
1个回答
0
投票

创建一个符合以下条件的结构 Decodable 协议,并添加所需属性

struct Country: Decodable {
    var name: String?
}
  • 创建一个 Country 对象型数组命名为 countryArray 在你们班
  • 执行HTTP调用
  • 从服务器上获取数据
  • 解析并加载到 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 对象符合 Decodable 协议的解析将在没有循环的情况下完成,因为该协议的 Struct 与您的JSON模式相匹配。

© www.soinside.com 2019 - 2024. All rights reserved.