-1

I want to sort the posts I read from JSON file on the server.

I want to sort via push of a button, sorted by name or time

My code

func ReadFromJson()
{
    let path="www.xxxxxxxxxxx.com/.json"
    let url=NSURL(string: path)
    let session=NSURLSession.sharedSession()
    let task=session.dataTaskWithURL(url!, completionHandler: { (data, response, err) -> Void in

        if (err == nil)
        {
            let dic = 
                 NSJSONSerialization.JSONObjectWithData(data, 
                     options: NSJSONReadingOptions.AllowFragments, error: nil) 
                     as NSDictionary

            self.arr=dic["events"] as? NSArray
            self.MyCollection.reloadData()
            self.Myind.stopAnimating()                
        }            
    })        
    task.resume()
}

1 Answer 1

1

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()
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

But I want when a button is pushed appears sort options by name, date, or time
Fine, so just re-sort the array depending upon which button was clicked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.