Populating table cells with data from Alamofire

For most of the day, I have been trying to play with Alamofire and use it to collect API based data to populate a table. I was able to get the data in my iOS app (I can print it to see it), but I can't for the rest of my life understand that the context is using my data to populate the correct number of table rows and set the label.

My data from the internet is like:

{
"members": [
    "Bob Dole",
    "Bill Clinton",
    "George Bush",
    "Richard Nixon",
    ]
}

      

My TableViewController has code like this:

...
var group: String?
var memberArr = [String]()
var member: [String] = []
...

override func viewDidLoad() {
    super.viewDidLoad()

    func getData(resultHandler: (data: AnyObject?) -> ()) -> () {
    Alamofire.request(.GET, "http://testurl/api/", parameters: ["groupname": "\(group!)"])
        .responseJSON { (_, _, JSON, _) in
            let json = JSONValue(JSON!)
            let data: AnyObject? = json
            let memberArr:[JSONValue] = json["members"].array!
            for obj in json["members"] {
                let member = obj.string!
            }
            resultHandler(data: data)
        }
    }
...



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

      

My return member Arr.count is not working

However, I can't figure out how to get the "member" variable available in the entire controller, as I would like to use it to return the correct number of rows or dynamically use the member list to set the title of each cell.

I know this is a newbie, but I dug up StackOverflow and none of the questions seemed to fit into my situation.

Thank you in advance!

+3


source to share


1 answer


What is happening is that getData has a completion block that runs in the background, you need to quickly report the table update after you finish reading the returned data, but you need to send that update back to the main thread:

func getData(resultHandler: (data: AnyObject?) -> ()) -> () {
Alamofire.request(.GET, "http://testurl/api/", parameters: ["groupname": "\(group!)"])
    .responseJSON { (_, _, JSON, _) in
        let json = JSONValue(JSON!)
        let data: AnyObject? = json
        let memberArr:[JSONValue] = json["members"].array!
        for obj in json["members"] {
            let member = obj.string!
        }
        resultHandler(data: data)
        dispatch_async(dispatch_get_main_queue()) {
            self.tableView.reloadData()
        }
    }
}

      



I hope this helps!

+3


source







All Articles