在选择器视图中从JSON加载数据

时间:2018-04-01 17:07:07

标签: ios swift alamofire uipickerview

我从服务器获取数据,并且我有以下JSON:

(
    {
        id = 1;
        status = 1;
        title = "jimmy";
    },
        {
        id = 2;
        status = 1;
        title = "arnold";
    },
        {
        id = 3;
        status = 1;
        title = "mike";
    }
)

我想在选择器视图中加载此JSON的标题,当我选择其中一个时,所选行的id在myID变量中设置。 我写了下面的代码但是选择器视图没有显示任何内容:

var dictionary = [[String : AnyObject]]()

override func viewDidLoad() {
    super.viewDidLoad()

    pickerDep.delegate = self
    pickerDep.dataSource = self

    var Token=FuncClass.ReadData(_file: "fileToken.txt")
    let url=Property._URL+"getTicketDepartment"
    let parameters = [
        "token": Token
    ]

    Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseJSON { response in
        if let data = response.data {
            let json = String(data: data, encoding: String.Encoding.nonLossyASCII)

            let result=response.result
            self.dictionary = (result.value as? [Dictionary<String,AnyObject>])!
        }
    }
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

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

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return dictionary[row]["title"] as! String
}

我该怎么办?

2 个答案:

答案 0 :(得分:1)

您需要在从Alamofire加载数据后重新加载选择器视图:

update-alternatives --config java

顺便说一句 - 为什么当你的属性包含数据数组时,你的属性名为Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseJSON { response in if let data = response.data { let json = String(data: data, encoding: String.Encoding.nonLossyASCII) let result=response.result if let array = result.value as? [Dictionary<String,AnyObject>] { self.dictionary = array pickerDep.reloadAllComponents() } } }

答案 1 :(得分:0)

这是一个老问题,但我也遇到了这个问题。当我在我的应用程序中使用 reloadAllComponents() 覆盖 func viewDidLoad() 时,我的应用程序挂断了 4-5 秒。然后刷新pickerView或崩溃。我通过添加 DispatchQueue 功能解决了这个问题。我对这篇文章的解决方案是,

DispatchQueue.main.async {
    pickerDep.reloadAllComponents()
}