UITableView problem when it does not retrieve data from BD

1

Hello, I have a problem, I am very new in swift, I made a UITableview taken from a mysql database, when the webservices bring me data, there is no problem, that is, the table is loaded with the corresponding data, but when the web services brings empty I get an error. The code that gives me error is the following:

func parseJSON() {

    var jsonResult: NSMutableArray = NSMutableArray()


    do{
        jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray

    } catch let error as NSError {
        print(error)

    }

    var jsonElement: NSDictionary = NSDictionary()
    let locations: NSMutableArray = NSMutableArray()

    for i in 0..<jsonResult.count
    {

        jsonElement = jsonResult[i] as! NSDictionary

        let location = ComunicadosLocationModel()


        if let mensaje = jsonElement["mensaje"] as? String,
            let fecha = jsonElement["fechapublicacion"] as? String,
                let estado = jsonElement["estado"] as? String

            {
                location.mensaje = mensaje
                location.fechapublicacion = fecha
                location.estado = estado

        }

        locations.addObject(location)

    }

    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        self.delegate.itemsDownloaded(locations)

    })
}

The line that marks me the error is

jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray

What could it be?

    
asked by Luis Adrian Carpio 02.09.2016 в 04:57
source

2 answers

1

It gives you an error because self.data is null

To avoid error and the app fails, you should do this:

if self.data != nil {
    jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
}

Haber if it works for you

    
answered by 27.09.2016 в 11:41
1

As mentioned by @ user9099 , the problem is in self.data .

When executed:

do{
    jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray

} catch let error as NSError {
    print(error)

}

An attempt is made to insert an jsonResult in JSONObject , but if there is an error, then whatever is inside the catch is executed. It comes empty self.data = nil , and therefore can not create the object JSONObject .

    
answered by 27.01.2017 в 19:47