首页 > 解决方案 > PickerView 未填充 json 数组

问题描述

我的视图控制器中有一个选择器视图,当我运行应用程序时,我尝试使用 alamofire 从我的 api 加载的数组填充它,在选择器视图中没有数据,但我在控制台中看到响应

控制台也正确返回响应为 arrayValue 控制台也正确返回响应为 arrayValue

调试它也没有错误

在此处输入图像描述

class AdPostViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var pickerView: UIPickerView!

    let SiteUrl = "https://xyz.co/apis/sections.php"
    var data = [JSON]()
    var sections = [JSON]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.getSections()
        pickerView.delegate = self
        pickerView.dataSource = self

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return sections.count
    }

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

    }


    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        if pickerView == pickerView {
            return sections.count
        }
        return 0
    }

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let Secname =  sections[row].string
        print(Secname!)
    }

    func getSections() {

        AF.request(SiteUrl).validate().responseJSON { response in
            switch response.result {
            case .success:
                print("Validation Successful)")

                if let json = response.data {
                    do{
                        let jsonData = try JSON(data: json)
                        self.data = jsonData.arrayValue
                        print("DATA PARSED: \(jsonData)")
                        for itemDict in self.data {
                            let name = itemDict["name"]
                            self.sections.append(name)
                            self.pickerView.reloadAllComponents()

                            print("Item name: \(self.sections)")
                        }

                    }
                    catch {
                        print("JSON Error", error)
                    }
                }
            case .failure(let error):
                print(error)
            }
        }
    }
    
}

这是在重新加载 pickerView 之后,它加载了部分名称分隔的字母!我的意思是它让很多采摘者每个人都有一个字母! 在此处输入图像描述

标签: iosswiftuiviewcontrolleralamofireuipickerview

解决方案


推荐阅读