Swift: 如何填充 UITableView

Swift: How to populate a UITableView

我正在尝试将函数 get() 的结果发送到 table 视图。此函数内的结果来自 Http post。所以我正在使用 nsmutableurl 等。我得到了可以在我的输出控制台中看到的数据,现在想要它出现在我的 table 视图中。我该怎么做?

我有这一堆代码,我设法获取了数据(可以在我的输出控制台中看到),现在我正在尝试将这些数据加载到 table 视图中。如何在 table?

中传递这些数据
    func get(){

        let request = NSMutableURLRequest(URL: NSURL(string: "http://myurl/somefile.php")!)
        request.HTTPMethod = "POST"
        let postString = "id=\(cate_Id)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in

            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        i need the count of the rows here
    }



    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        land want to display the data inside each cell

    }

由于您没有提供有关 HTTP 请求结果的任何类型的信息,我试图在 "general way" 中回答您。

通常,您会收到所需数据的字典数组形式的响应。为了简单起见:假设您正在请求字符串,那么您必须这样做:

let myStringArray: [String] = []

在您的 HTTP 响应块中,您接受了您的响应,请注意!此代码完全取决于您的响应树。我不知道你的反应是什么,因为你没有提供。

        if let JSON = response.result.value {

            let myString = String((JSON.valueForKey("stringWithinMyResonseTree"))!)
            myStringArray.append(myString)

            self.tableView.reloadData()
        }

那么你的行数是:

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

在 Cell 上,这取决于您想用它做什么。例如,如果您的 Cell 中有一个 Label 并且想要在其上显示您的 String 的值,您将创建一个 UITableViewCell 子类并调用它,例如 MyCell。在 MyCell 中,您可以像这样创建标签的 Outlet:

class MyCell: UITableViewCell {

    @IBOutlet weak var myLabel: UILabel!

然后您需要 return 您的 UITableView 子类并用所需的字符串填充标签。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell
        let string = myStringArray[indexPath.row]
        cell.myLabel.text = string

        return cell

}

不要忘记在 Interface Builder 属性中设置 Cell 标识符。

您的请求需要一个包含一个字典的数组,但您将其转换为字符串。因此,请使用以下内容代替 get() func:

func download() {
    let requestURL: NSURL = NSURL(string: "http://myurl/somefile.php")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                let grouID = String(json.valueForKey("group_id"))
                let name = String(json.valueForKey("NAME"))

                print("grouID = \(grouID)")
                print("name = \(name)")
                print("debug: this code is executed")

            }catch {
                print("Error with Json: \(error)")
            }

        }
    }

    task.resume()
}

要调试您的问题,请创建异常断点: