2017-02-14 5 views
1

출력 JSON이 경우Swift 3.0에서 TableViewCell으로 JSON 출력을 선택하는 방법은 무엇입니까?

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

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

에게

TableViewCell.swift 코드를 아래와 같이 스위프트 3.0 TableViewCell에 내 질문을 "디스플레이" 출력을 검색 할 수 JSO가 어떻게 수정합니까? N 출력은 위의 TableViewCell에서 이와 유사합니까? PHP로 인해

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

JSON 출력, I는 출력을 생성하기 위해 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(); 
    } 
?> 

내 목표는 스위프트 3.0 정수로 "디스플레이" 출력을 설정하는 것입니다. 일반적으로 아래 JSON 출력을 검색하여 Integer로 설정하려면 아래 코드를 사용하십시오.

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에서 test.swift, 나는 그것을 사용하는 방법을 모르겠어요. 누군가가 도울 수 있으면 감사합니다.

감사합니다.

+0

두 번째 하나를 사용 Array 유형 비교할 수 있습니다 " 1 ","refno ":"1111 ","dtfrom ":"2017-12-15 "}'. 두 가지 응답이 아닙니다. 권리? –

+0

예. 한 번에 하나의 값만 표시합니다 – Jamilah

+0

이 단일 레코드를'tableView'에 표시하고 싶습니까? 또한'show display = Int (json [ "display"]!) 행으로'display'에서 값을 가져올 수 있습니까? '? –

답변

1

당신은 당신의 JSON 응답이 Dictionary 나`당신의 JSON 응답은 당신에게 { "디스플레이"를 한 번에 하나의 객체, 배수가 아닌 수단을 줄 것이다 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 {} 
+0

좋아, 먼저 해보겠습니다. 감사합니다 btw – Jamilah

+0

@ Jamilah 귀하의 답변을 기다릴 것입니다 :) –

+0

코드를 실행할 수 없습니다. 나는 이것을 좋아하지만 일을하지 않았다. do { let JSONSerialization.jsonObject (with : data!)를 AnyObject로 사용하자. if array = json as? [문자열 : 없음] { 하자 운동 = 지능 (! JSON [ "이동"]) 경우 (운동 == 1) { 인쇄 ("테스트") 창 } 인쇄 (어레이) } } catch {} – Jamilah