Sorting UITableViewData from AlamoFire with an escaping closure

263 views Asked by At

I'm trying to sort and section a UTableView with a Custom Cell Alphabetically. In my ViewController I have a function that downloads the JSON data then stores it in a Dictionary.

var attendees = [Attendee]()
var sortedFirstLetters: [String] = []
var sections: [[Attendee]] = [[]]

func downloadAttendeeData(completed: @escaping DownloadComplete) {
    let headers: HTTPHeaders = [

        "Accept": "application/json;odata=verbose",
        "User-Agent": "iOS;iOS"

    ]

    NetworkManager.sharedInstance.manager.request(Attendee_URL, method: .get, headers: headers)
        .responseJSON { response in

            let result = response.result

            if let dict = result.value as? Dictionary<String, AnyObject> {

                if let list = dict["d"]?["results"] as? [Dictionary<String, AnyObject>] {

                    for att in list {
                        let attendee = Attendee(AttendeeDict: att)
                        self.attendees.append(attendee)

                    }


                    self.tableView.reloadData()

                }

            }

            completed()
    }


}

This piece of code is exactly what I need

    let firstLetters = self.attendees.map { $0.titleFirstLetter }
    let uniqueFirstLetters = Array(Set(firstLetters))
    self.sortedFirstLetters = uniqueFirstLetters.sorted()

    self.sections = self.sortedFirstLetters.map { firstLetter in
        return self.names
            .filter { $0.titleFirstLetter == firstLetter }
            .sorted { $0.titleAD < $1.titleAD }
    }

However when I put this code in viewDidLoad it produces and Empty Array.

override func viewDidLoad() {
    super.viewDidLoad()


    tableView.delegate = self
    tableView.dataSource = self
    searchBar.delegate = self

    let firstLetters = self.attendees.map { $0.titleFirstLetter }
    let uniqueFirstLetters = Array(Set(firstLetters))
    self.sortedFirstLetters = uniqueFirstLetters.sorted()

    self.sections = self.sortedFirstLetters.map { firstLetter in
        return self.names
            .filter { $0.titleFirstLetter == firstLetter }
            .sorted { $0.titleAD < $1.titleAD }
    }

    self.downloadAttendeeData {


    }



}

If I put the code inside the self.downloadAttendeeData declaration it produces data but it doesn't create the table sections.

How can I produce the sections after the data is loaded into the tableView? Is that the problem?

1

There are 1 answers

0
infinite-loop On BEST ANSWER

Make sure that you call tableView.reloadData() from the main thread like this:

dispatch_async(dispatch_get_main_queue()) { 
   self.tableView.reloadData()
}

or in Swift 3 and later:

DispatchQueue.main.async {
  self.tableView.reloadData()
}