We would need to see more detail on the structure of the events array, but if you're going to use NSArray, then you'd use one of the many NSArray sorting methods.
First, let's assume that the JSON looked like:
{
"events": [
{
"name": "Storming of the Bastille",
"date": "July 7, 1789"
},
{
"name": "american revolution",
"date": "July 4, 1776"
},
{
"name": "Guy Fawkes Night",
"date": "November 5, 1605"
}
]
}
If you wanted to sort that by name, you could:
var error: NSError?
if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSDictionary {
if let unsortedEvents = json["events"] as? NSArray {
let descriptor = NSSortDescriptor(key: "name", ascending: true, selector: "caseInsensitiveCompare:")
self.events = unsortedEvents.sortedArrayUsingDescriptors([descriptor])
self.collectionView.reloadData()
self.activityIndicatorView.stopAnimating()
}
}
Clearly, if the dates were in a form that could be sorted alphabetically, you could do something like the above. I picked formats that were not in an easily sorted form, to illustrate a more complicated combination of NSDateFormatter and sortedArrayUsingComparator
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM d, YYYY"
var error: NSError?
if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSDictionary {
if let unsortedEvents = json["events"] as? NSArray {
self.events = unsortedEvents.sortedArrayUsingComparator() { (obj1, obj2) -> NSComparisonResult in
let event1 = obj1 as NSDictionary
let event2 = obj2 as NSDictionary
let date1 = formatter.dateFromString(event1["date"] as NSString)
let date2 = formatter.dateFromString(event2["date"] as NSString)
return date1!.compare(date2!)
}
self.collectionView.reloadData()
self.activityIndicatorView.stopAnimating()
}
}