Sarah Malik Sarah Malik - 1 month ago 8
Swift Question

Swift: How to populate a UITableView

I am trying to get the results from the function get() to the tableview. the result inside this function comes from Http post. So i am using nsmutableurl etc. i get the data n can see in my output console and now want it on my tableview. how can i do this?

I have this bunch of code, I managed to fetch the data (can see in my output console) and now I am trying to load these data on the table view. How can I pass this data inside the 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

}

Answer

Since you're not providing any kind of information about your HTTP Request result, I'm trying to answer you in a "general way".

In general you get a response as an Array of Dictionaries of your desired data. To make it easy: Let's say you're requesting Strings, then you have to do it like this:

let myStringArray: [String] = []

Within your HTTP response block you take your response and please beware! This Code depends completely on YOUR response tree. I have no idea what your response it, since you haven't provided it.

        if let JSON = response.result.value {

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

            self.tableView.reloadData()
        }

Then you have your numbers of rows with:

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

On the Cell it depends on what you want to do with it. If you have for example a Label within your Cell and want to display the value of your String on it, you would create a UITableViewCell subclass and call it for example MyCell. In MyCell you create an Outlet of your Label like this:

class MyCell: UITableViewCell {

    @IBOutlet weak var myLabel: UILabel!

Then you need to return your UITableView subclass and populate the Label with the desired String.

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

}

Don't forget to set the Cell identifier within the Interface Builder properties.

Your request expects an Array of one Dictionary, but you cast it as a String. So instead of your get() func, please use the following:

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()
}

To debug your problems, please create an exception breakpoint:

enter image description here