如何在Swift 3.0中将JSON数据提取到UIPickerView?

时间:2017-02-13 02:56:43

标签: php ios swift3 xcode8 uipickerview

我的问题是,如何在Swift 3.0中将数据从PHP提取到UIPickerView中?

目前,我有UIPickerView的这些代码来创建下拉列表。现在,我只能根据xcode var department = ["ICTD","FAD","PSD"]

中的变量声明显示下拉列表值

dropdown.swift

import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
    @IBOutlet var departmentLbl: UITextField!
    @IBOutlet var dropdownLbl: UIPickerView!
    @IBOutlet var outputLbl: UILabel!

    @IBOutlet var user_idLbl: UILabel!

    var department = ["ICTD","FAD","PSD"]

    var user_id: String!

    override func viewDidLoad() { 
        super.viewDidLoad() 

        user_id = "ID001" // these value that need to be past to PHP

        let url = URL(string: "http://localhost/getdepartment.php")
        let session = URLSession.shared
        let request = NSMutableURLRequest(url: url! as URL)
        request.httpMethod = "POST"
        let LoginDataToPost = "user_id=\(user_id!)"
        request.httpBody = LoginDataToPost.data(using: String.Encoding.utf8)
        let task = session.dataTask(with: request as URLRequest, completionHandler: {
            (data, response, error) in
            if error != nil { return }
            else {
                do {
                    if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String] {
                        DispatchQueue.main.async {
                                let display     = Int(json["display"]!)
                                let realname    = json["real_name"]
                                let department  = json["dept"]

                                if(display == 1) {
                                    // dropdown list value display here
                                    return
                                }
                                else { return }
                        }  
                    }
                    else { }
                }
                catch {}
            }
        })
        task.resume()
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        var countrows : Int = department.count
        if pickerView == dropdownLbl {
            countrows = self.department.count
        }
        return countrows
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if pickerView == dropdownLbl {
            let titleRow = department[row]
            return titleRow
        }
        return ""
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView == dropdownLbl {
            self.departmentLbl.text = self.department[row]
            self.dropdownLbl.isHidden = true
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {   
        if (textField == self.departmentLbl) {
            self.dropdownLbl.isHidden = false
        }
    }

}

我有这些PHP代码可以输出

真实姓名部门

基于x code

中的 user_id

getdepartment.php

<?php
    $connect = mysqli_connect("","","","");
    global $connect;

    if (isset($_POST['user_id'])) { 

        $user_id = $_POST['user_id'];

        $sql = "SELECT * FROM table WHERE user_id ='$user_id'";
        $result = mysqli_query($connect,$sql);
        if($result && mysqli_num_rows($result)>0){
            while ($row = mysqli_fetch_array($result)) {

                $real_namedb = $row['real_name'];
                $dept_db     = $row['dept'];

                $output = array('real_name' => $real_namedb, 'dept' => $dept_db);
                echo json_encode($output);
            }
        mysqli_free_result($result);
        }
        else { }
    }
?>

这些PHP提供了如下JSON数据的输出:

 {"display":"1","real_name":"NAME TEST 1","dept":"ICTD"}
 {"display":"1","real_name":"NAME TEST 2","dept":"ICTD"}

感谢有人可以提供帮助。

感谢。

1 个答案:

答案 0 :(得分:2)

我相信您应该根据从服务器收到的值创建下拉列表。根据您在问题中给出的代码,我发现您没有将从服务器获得的部门名称添加到阵列中。

您可以进行以下更改并观察:

if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
    DispatchQueue.main.async 
    {
       let display = Int(json["display"]!)
       let realname = json["real_name"]
       let departmentName = json["dept"]

       if(display == 1) {
          // dropdown list value display here
          self.department.append(departmentName)
          self.dropdownLbl.reloadAllComponents() // this is reference to your pickerView. Make it global and use it
          return
       }else { return }
    }  
}

如果它能解决问题,请告诉我......