【问题标题】:How to select JSON output into TableViewCell in Swift 3.0 ?如何在 Swift 3.0 中选择 JSON 输出到 TableViewCell 中?
【发布时间】:2017-02-14 09:52:58
【问题描述】:

如果这些JSON输出

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

可以在 Swift 3.0 TableViewCell 中检索 "display" 输出,如下面的代码

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

我的问题是,如果 JSON 输出在上面的 TableViewCell 中看起来像这样,我该如何修改它?

JSON 输出

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

因为在 PHP 中,我将 "display" 设置为 1、2 和 3 以产生输出。

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();
    }
?>

我的目标是在 Swift 3.0 中将 "display" 输出设置为整数。通常我使用下面的代码来检索这些 JSON 输出并将其设置为整数。

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

但是在TableViewCell中,我不知道怎么用。感谢有人可以提供帮助。

谢谢。

【问题讨论】:

  • 第二个会给你一个对象,而不是多个方法一次你的 JSON 响应只有{"display":"1", "refno":"1111","dtfrom":"2017-12-15"}。不是两个回应。对吗?
  • 是的。它一次只显示一个值
  • 您想在tableView 中显示此单条记录吗?您还可以通过let display = Int(json["display"]!) 行在display 中获得价值吗?
  • 不。如果 JSON 输出像第二个,我无法获得 display 的值。仅当 JSON 输出为第一时才有效
  • 我应该将此作为解决方案发布吗?您愿意接受吗?

标签: php json swift3 tableviewcell


【解决方案1】:

您可以使用 if let 比较您的 JSON 响应是 DictionaryArray 类型

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

【讨论】:

  • @Jamilah Ok 将等待您的回复 :)
  • 无法运行代码。我尝试这样,但没有用。 do { let json = try JSONSerialization.jsonObject(with: data!) as AnyObject if let array = json as? [[String:Any]] { let motion = Int(json["movement"]!) if(movement == 1) { print("test") return } print(array) } } catch {}
  • @Jamilah 为什么您要尝试将其转换为 anyObject,不要那样做,movement 是什么,您的回复中没有像 movement 这样的东西。你也使用 json 而不是数组或字典,就像我的解决方案一样。
  • 哎呀。对不起 。我的意思是“展示”
  • 你能在你的 // 响应中添加示例是数组部分,所以我可以在我的代码中尝试一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多