我无法从数据库加载数据以显示UIPickerView的结果

时间:2019-05-28 09:45:09

标签: json swift

我无法从数据库加载数据以显示UIPickerView的结果。我通过修复数组值UIPicker进行测试,可以将数据加载到pickerView中,但是当我使用数组加载时,json UIPickerViewDataSource无法加载到选择器视图中

可以加载

var team = ["Apple", "Banana", "Tomato", "Corn", "Bean", "Orange", "Mango", "Mangoteen"]

无法加载

var team: [AnyObject] = []


import UIKit

class getAllTeamViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate, UITextFieldDelegate {

var selectValue: String?

@IBOutlet weak var showSelectValuePickerView: UITextField!

// Array
    //var team = ["Apple", "Banana", "Tomato", "Corn", "Bean", "Orange", "Mango", "Mangoteen"]
    var team: [AnyObject] = []

//Function getValue from database
func getvalue() -> Void {
    //get the values from sql/Json
    let url = NSURL(string: "http://www.test.com/myWebService/getteamPickView.php")

    let data = NSData(contentsOf: url! as URL)
    var jsonResponse = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
        jsonResponse = jsonResponse.reversed() as NSArray
        reloadInputViews()
        print("jsonResponse ==> \(jsonResponse)")

    for candidate in jsonResponse {
        if let cdict = candidate as? NSDictionary {
            //fullName is the column name in sql/json
            let names = cdict["NameTeam"]
            self.selectValue?.append(((names! as AnyObject) as! String))
            print("Names ==> \(String(describing: names))")
        }//if
    }//for
}//getvalue

//  Picker View Function
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

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

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    let titleRow = (team[row] )
    return titleRow as? String
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    if team.count > 0 && team.count >= row{
        self.showSelectValuePickerView.text = self.team[row] as? String 
        self.showSelectValuePickerView.isHidden = true
    }
}

}

1 个答案:

答案 0 :(得分:0)

对不起,这确实是错误的代码。有很多不良做法。

  • 如果显然是[AnyObject],则不要将数组声明为[String]
    这避免了像names! as AnyObject) as! String
  • 这样的可怕类型转换
  • 在Swift中请勿使用NSDataNSURLNSArrayNSDictionary。使用本机类型。
  • .mutableContainers在Swift中毫无意义,请省略整个参数。
  • 从不使用Data(contentsOf从远程URL同步加载数据。
  • 始终在主线程上重新加载UI。
  • 处理所有错误!至少print个。

发生此错误是因为您在填充数据源数组之前调用了reloadInputViews()(我假设它会重新加载选择器视图)。

而不是填充数据源数组team,而是将字符串附加到selectValue上。

这是代码的稍微优化的版本

@IBOutlet weak var showSelectValuePickerView: UITextField!

var team = [String]()

//Function getValue from database
func getvalue() {
    //get the values from sql/Json
    let url = URL(string: "http://www.test.com/myWebService/getteamPickView.php")!
    let task = URLSession.shared.dataTask(with: url) { (data, _ , error) in
        if let error = error { print(error); return }
        do {
            if let jsonResponse = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
                self.team = jsonResponse.compactMap{ $0["NameTeam"] as? String }
                DispatchQueue.main.async {
                    self.reloadInputViews()
                }
            } else { print("JSON is not an array") }
        } catch { print(error) }
    }
    task.resume()
}

//  Picker View Function
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

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

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    self.showSelectValuePickerView.text = self.team[row]
    self.showSelectValuePickerView.isHidden = true // Are you serious ??? This hides the text field
}