[英]How to select JSON output into TableViewCell in Swift 3.0 ?
If these JSON output如果这些JSON输出
{
"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可以像下面的代码一样在Swift 3.0 TableViewCell 中检索“显示”输出
TableViewCell.swift 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 输出在上面的 TableViewCell 中看起来像这样,我该如何修改它?
JSON output JSON 输出
{"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.因为在 PHP 中,我将“显示”设置为 1、2 和 3 以生成输出。
display.php显示.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.我的目标是在 Swift 3.0 中将“显示”输出设置为整数。 Normally I use code below to retrieve those JSON output and set it as Integer.通常我使用下面的代码来检索那些 JSON 输出并将其设置为整数。
test.swift测试.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.但是在TableViewCell中,我不知道如何使用它。 Appreciate if someone can help.感谢有人可以提供帮助。
Thanks.谢谢。
You can compare your JSON response is Dictionary
or Array
type using if let
您可以使用if let
比较您的 JSON 响应是Dictionary
还是Array
类型
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 {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.