简体   繁体   English

使用Swift在TableView中显示JSON数据

[英]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 . 我正在尝试显示从数据库中获取的一些数据到TableView但该数据未显示在TableView The data I receive is formatted in JSON. 我收到的数据以JSON格式格式化。

This is the data I receive form the data base and what I want to print in the TableView is just David: 这是我从数据库收到的数据,我想在TableView打印的只是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: arrayData是一个array ,我将从数据库中接收的数据放入该array ,并声明如下:

var arrayData: [String] = []

The code 编码

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

show in the console this Data1:["David"] , so I get the data correctly. 在控制台中显示此Data1:["David"] ,这样我就可以正确获取数据。

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 . 然后,我实现了要在“ TableView”中打印的方法, numberOfSectionsInTableView方法, numberOfRowsInSection方法和cellForRowAtIndexPath方法,但是数据没有在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. 我认为问题在于TableView是在将数据放入array之前绘制的,因此它不打印任何内容,因为数组为空,而且我不知道如何解决它。

Anyone knows what is my problem? 有人知道我有什么问题吗?

yes, you're right. 你是对的。

session.dataTaskWithRequest session.dataTaskWithRequest

is async. 是异步的。 Data is not returned immediately, it have delay. 数据不会立即返回,它会延迟。 You must to reload tableview after recieved data: 您必须在收到数据后重新加载tableview:

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: 在viewdidload中,我将调用:

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

it 's better 更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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