从json获取数据并显示在选择器中

时间:2019-04-22 11:23:54

标签: swift picker

我试图从json网址中获取数据并显示在选择器中,但它第一次不在Swift中显示。请检查我的代码。

import UIKit

class PickerVC: UIViewController ,UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate{
    @IBOutlet weak var txtEmail: UITextField!
    @IBOutlet weak var txtPassword: UITextField!
    @IBOutlet weak var view1: UIView!
    var myPickerView : UIPickerView!
    //  var pickerData = ["Hitesh Modi" , "Kirit Modi" , "Ganesh Modi" , "Paresh Modi"]
    var pickerData: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        let emailImage = UIImage(named:"email")
        addLeftImageTo(txtField: txtEmail, andImage: emailImage!)

        let passwordImage = UIImage(named:"User")
        addLeftImageTo(txtField: txtPassword, andImage: passwordImage!)

        self.txtEmail.addTarget(self, action: #selector(self.textDidChange), for: UIControl.Event.editingDidEnd)
    }
    func pickUp(_ textField : UITextField){
        print("pick up...T")
        // UIPickerView
        self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
        self.myPickerView.delegate = self
        self.myPickerView.dataSource = self
        self.myPickerView.backgroundColor = UIColor.white
        textField.inputView = self.myPickerView

        // ToolBar
        let toolBar = UIToolbar()
        toolBar.barStyle = .default
        toolBar.isTranslucent = true
        toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
        toolBar.sizeToFit()

        // Adding Button ToolBar
        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneClick))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ViewController.cancelClick))
        toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        textField.inputAccessoryView = toolBar

    }
    //MARK:- PickerView Delegate & DataSource
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        print("no. of components...")
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        print("no. of rows...")

        return pickerData.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        print("title for Row...")

        return pickerData[row]
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print("did select picker...")
        self.txtPassword.text = pickerData[row]
    }
    //MARK:- TextFiled Delegate
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("did Edit...")
        //        self.txtEmail.addTarget(self, action: #selector(self.textDidChange), for: UIControl.Event.editingDidEnd)
        self.pickUp(txtPassword)

        //getDaTa()
    }



    //MARK:- Button
    @objc func doneClick() {
        txtPassword.resignFirstResponder()
    }
    @objc func cancelClick() {
        //        txtPassword.resignFirstResponder()
    }

    @objc func textDidChange(_ textField:UITextField) {
        print("text did change called....")
        var value=self.txtEmail.text!
        //start
        let url = URL(string: "http://www.json-generator.com/api/json/get/ceBRtExBaq?indent=2")!
        var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData,timeoutInterval: 10000)
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }
            do {
                if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [String:AnyObject] {
                    print("json:\(jsonData)")

                    DispatchQueue.main.async {
                        //                     self.pickUp(self.txtPassword)
                        if let pumpData = jsonData["User"]  as? [[String:AnyObject]] {
                            for i in pumpData{
                                self.pickerData.append(String(describing:i["Type"]!))
                                self.pickUp(self.txtPassword)

                            }
                        }
                    }

                }
            }
            catch let error as NSError {
                print(error)
            }
            }.resume()
        //end

    }


}

2 个答案:

答案 0 :(得分:1)

从URL提取数据时,您应该使用MVC模式,使用委托,重新加载pickerView。

这是我的协议:

protocol DataSourceDelegate {
    func categoriesLoaded(categories: [Category])
}

这是我的提取函数:

func loadCategories(monthID: Int) {
        let session = URLSession.shared
        let request = URLRequest(url: URL(string: "http://manage.littlesleeperapp.com/api/v1/tip_category/get_categories_tips_by_segment_id/\(monthID)")!)
        session.dataTask(with: request) { (data, response, error) in
            if (response as? HTTPURLResponse) != nil {
                let jsonData = try! JSONDecoder().decode(Dictionary<String, [Category]>.self, from: data!)
                let categories = jsonData["data"]!
                self.categories = categories
                self.delegate?.categoriesLoaded(categories: categories)
            }
            }.resume()
    }

完成提取类别后,就会调用已加载的委托。

然后重新加载tableView

extension TipsViewController: DataSourceDelegate {
    func categoriesLoaded(categories: [Category]) {
        DispatchQueue.main.async {
            self.categories = categories
            self.myTableView.reloadData()
            self.activityIndicator.stopAnimating()
        }
    }
}

答案 1 :(得分:1)

从服务器获取数据后,可能需要重新加载pickerView 如果不起作用,请在获取数据后检查,是否运行pickerView的委托