简体   繁体   中英

How to select JSON output into TableViewCell in Swift 3.0 ?

If these JSON output

{
    "status":"ok",
    "display": [{"refno":"1111", "dtfrom":"2017-12-12"},{"refno":"2222","dtfrom":"2017-12-15"}]
}

Can retrieve "display" output in Swift 3.0 TableViewCell like below code

TableViewCell.swift

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableview: UITableView!
    var movementstatus: [MovementStatus]? = []
    var detailsVC : MovementDetailsVC?

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchMovement()
    }

    func fetchMovement() {
        let urlRequest = URLRequest(url: URL(string: "http://localhost/get.json")!)
        let task = URLSession.shared.dataTask(with: urlRequest) {
            (data,response,error)in
            if error != nil {return}

            self.movementstatus = [MovementStatus]()
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
                if let msFromJson = json["display"] as? [[String: AnyObject]]{
                    for mFromJson in msFromJson
                    {
                        let ms = MovementStatus()
                        if let dtfrom = mFromJson["dtfrom"] as? String, let refno  = mFromJson["refno"] as? String {
                            ms.dtfrom       = dtfrom
                            ms.refno        = refno
                        }
                        self.movementstatus?.append(ms)
                    }
                }
                DispatchQueue.main.async {
                    self.tableview.reloadData()
                }
            }
            catch let error{ print(error)}
        }
        task.resume()
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "movementCell", for: indexPath) as! MovementStatusCell
        cell.dtfromLbl.text         = self.movementstatus?[indexPath.item].dtfrom
        cell.refnoLbl.text          = self.movementstatus?[indexPath.item].refno
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.movementstatus?.count ?? 0
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (detailsVC == nil) {
            detailsVC = self.storyboard?.instantiateViewController(withIdentifier: "MovementDetails") as? MovementDetailsVC
        }
        detailsVC?.move = self.movementstatus?[indexPath.item]
        self.navigationController?.pushViewController(detailsVC!, animated: true)
    }
}

My question is how do i modify it if the JSON output look like this in TableViewCell above ?

JSON output

{"display":"1", "refno":"1111","dtfrom":"2017-12-15"}
{"display":"1", "refno":"2222","dtfrom":"2017-12-20"} 

Because in PHP, I set the "display" as 1, 2, and 3 to produce an output.

display.php

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

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

        $sql    = "SELECT * FROM table";
        $result = mysqli_query($connect, $sql);

        if ($result && mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_array($result)) {

                $refnodb     = $row['refno'];
                $dtfromdb    = $row['dtfrom'];

                $output= array('display' => '1', 'refno' => $refnodb, 'dtfrom' => $dtfromdb);
                echo json_encode($output);
                exit();
            }
        mysqli_free_result($result);
        }
        else {
            $output = array('display' => '2', 'refno' => 'value not found !');
            echo json_encode($output);
            echo mysqli_error($connect);
            exit();
        }
    }
    else {
        $output = array('message' => '3', 'refno' => 'No value post yet !');
        echo json_encode($output);
        exit();
    }
?>

My goal is to set "display" output as Integer in Swift 3.0. Normally I use code below to retrieve those JSON output and set it as Integer.

test.swift

import UIKit
class LoginViewController: UIViewController {
    @IBOutlet var valueLbl: UITextField!
    var value: String!    
    override func viewDidLoad() { super.viewDidLoad()}

    @IBAction func sendData(_ sender: Any) {
        value = valueLbl.text
        let url     = URL(string: "http://localhost/get.php")
        let session = URLSession.shared
        let request = NSMutableURLRequest(url: url! as URL)
        request.httpMethod = "POST"
        let DataToPost = "submit=\(value!)"
        request.httpBody = DataToPost.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 refno       = json["refno"]
                                let dtfrom      = json["dtfrom"]

                                if(display == 1) {
                                    return
                                }
                                else if(display == 2) {
                                    return
                                }
                                else if(display == 3) {
                                    return
                                }
                        }  
                    }  
                }
                catch {}
            }
        })
        task.resume()
    }
}

But in TableViewCell, I don't know how to use it. Appreciate if someone can help.

Thanks.

You can compare your JSON response is Dictionary or Array type using if let

do {
    let json = try JSONSerialization.jsonObject(with: data!) 
    if let array = json as? [[String:Any]] {
        //response is array
    }
    if let dictionary = json as? [String:Any] {
        if let display = dictionary["display"] as? String,
           let refno = dictionary["refno"] as? String,
           let dtfrom = dictionary["dtfrom"] as? String {

            print(display)
            print(refno)
            print(dtfrom)
        }
    }
} 
catch {}

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