Swift 2 - Variable with null value

2

I have a web page that returns the following json structure:

[  
   {  
      "nomeDoServico":"fdPHost",
      "nomeParaExibicao":"Host de Provedor da Descoberta de Função",
      "status":"Iniciado"
   },
   {  
      "nomeDoServico":"LanmanWorkstation",
      "nomeParaExibicao":"Estação de trabalho",
      "status":"Iniciado"
   }
]

The code below written in Swift 2 should take this return and by time fill the tableView with only the value serviceName. However, when I print I see that the QueryService function was not able to populate the Values variable:

import UIKit

class ViewController: UIViewController, UITableViewDelegate {

    var valores = [Dictionary<String, String>]()

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return valores.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
        let valor = valores[indexPath.row]
        cell.textLabel?.text = valor["nomeDoServico"]
        return cell
    }

    func consultarServico() -> Void
    {
        let myUrl = NSURL(string: "http://192.168.56.101/database_servico.php")
        let request = NSMutableURLRequest(URL:myUrl!)

        let postString:String = "id_menu=1"
        request.HTTPMethod = "POST"
        request.timeoutInterval = 5.0

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in

            if (error?.code == -1001)
            {
                print("Opa, timeout")
            }

            do {
                let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [Dictionary<String, String>]
                self.valores = jsonResult
            }
            catch
            {
                print("Erro ao buscar os dados")
            }
        }

        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // ocultar teclado ao clicar na view
        let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
        self.view.addGestureRecognizer(tap)

        consultarServico()
    }

    // encerra o teclado
    func DismissKeyboard(){
        self.view.endEditing(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Could someone please help me?

    
asked by anonymous 24.09.2015 / 06:29

1 answer

1

I tested here with your code and the return is saved in the variable normally.

You just need to change some points.

1) Your json is array and not dicionary , change to:

  

var values: NSArray = []

2) When you receive the data in the request change to:

  

let jsonResult = try NSJSONSerialization.JSONObjectWithData (data !, options: NSJSONReadingOptions.MutableContainers) as! NSArray

3) Give reload to the table as soon as you get the data:

  

self.tableView.reloadData ()

4) No tableView(_:numberOfRowsInSection:) change to:

  

let value = values [indexPath.row] as! NSDictionary

     

cell.textLabel? .text = value ["hostname"] as? String

Follow the complete code

class TesteViewController: UIViewController, UITableViewDelegate {

    var valores: NSArray = []

    @IBOutlet weak var tableView : UITableView!

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return valores.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
        let valor = valores[indexPath.row] as! NSDictionary
        cell.textLabel?.text = valor["nomeDoServico"] as? String
        return cell
    }

    func consultarServico() -> Void
    {
        let myUrl = NSURL(string: "http://fabiojanio.com/json/json.php")
        let request = NSMutableURLRequest(URL:myUrl!)

        let postString:String = "id_menu=1"
        request.HTTPMethod = "POST"
        request.timeoutInterval = 5.0

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in

            if (error?.code == -1001)
            {
                print("Opa, timeout")
            }

            do {
                let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray

                self.valores = jsonResult

                self.performSelectorOnMainThread(Selector("atualizaTabela"), withObject: nil, waitUntilDone: false)
            }
            catch
            {
                print("Erro ao buscar os dados")
            }
        }


        task.resume()
    }

    func atualizaTabela(){
        self.tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // ocultar teclado ao clicar na view
        let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
        self.view.addGestureRecognizer(tap)

        consultarServico()
    }

    // encerra o teclado
    func DismissKeyboard(){
        self.view.endEditing(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
    
24.09.2015 / 21:31