简体   繁体   中英

Show JSON data in a TableView with Swift

I am trying to display some data I take from a data base into a TableView but the data is not shown in the TableView . The data I receive is formatted in JSON.

This is the data I receive form the data base and what I want to print in the TableView is just David:

{"name":"David"}

This is the code to get the data from de data base:

let session = NSURLSession.sharedSession()
    let request = NSURLRequest(URL: NSURL(string: "http://localhost:8888/Patients.php")!)
    let task = session.dataTaskWithRequest(request) {data, response, downloadError in

        if let error = downloadError {
            print("Could not complete the request \(error)")
        }
        else {

            do {
                self.json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            } catch {
                fatalError()
            }
            dispatch_async(dispatch_get_main_queue(), {

                if let parseJSON = self.json{

                    let name = parseJSON["name"] as! String

                    self.arrayData.append(name)

                    print("Data1:\(self.arrayData)")
                }

            })
        }
    }
    task.resume()

arrayData is an array where I put the data I receive from the data base and it is declared like this:

var arrayData: [String] = []

The code

print("Data1:\(self.arrayData)")

show in the console this Data1:["David"] , so I get the data correctly.

Then I implement the methods to print in the ´TableView´, the numberOfSectionsInTableView method, the numberOfRowsInSection method and the cellForRowAtIndexPath method but the data is not printed in the TableView .

I think the problem is that the TableView is drawn before I put the data in the array so it prints nothing because the array is empty, and I don´t know how to fix it.

Anyone knows what is my problem?

yes, you're right.

session.dataTaskWithRequest

is async. Data is not returned immediately, it have delay. You must to reload tableview after recieved data:

self.arrayData.append(name)
self.tableview.reloadData()

Usually i will use block:

func getData(handleComplete:((arr:NSMutableArray)->())){
    let aray = NSMutableArray()
    let session = NSURLSession.sharedSession()
    let request = NSURLRequest(URL: NSURL(string: "http://localhost:8888/Patients.php")!)
    let task = session.dataTaskWithRequest(request) {data, response, downloadError in

        if let error = downloadError {
            print("Could not complete the request \(error)")
        }
        else {

            do {
                self.json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            } catch {
                fatalError()
            }
            dispatch_async(dispatch_get_main_queue(), {

                if let parseJSON = self.json{

                    let name = parseJSON["name"] as! String

                    aray.append(name)

                    print("Data1:\(self.arrayData)")
                }
                handleComplete(aray)

            })
        }
    }
    task.resume()
    arrayData
}

and in viewdidload i will call:

override func viewDidLoad() {
    super.viewDidLoad()
    self.getData { (arr) -> () in
        self.tableview.reloadData()
    }
}

it 's better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM