简体   繁体   中英

How to fetch JSON data into UIPickerView in Swift 3.0 ?

My question is, how to fetch data from PHP into UIPickerView in Swift 3.0 ?

Currently, I have these code for UIPickerView to create dropdown list. Right now, I can only display the dropdown list value based on variable declare inside 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
        }
    }

}

And I have these PHP code that gives an output of

real name and department

based on user_id value from x code

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 { }
    }
?>

These PHP gives an output of JSON data as below:

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

Appreciate if someone can help.

Thanks.

I believe you are supposed to create the dropdownlist based on values you received from server. Based on the code you've given in the question, I observed that you were not adding department names you got from the server to your array.

You can make following changes and observe:

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 }
    }  
}

Please let me know if it resolves the problem or not...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM