如何对从Swift中的JSON服务器文件中读取的帖子进行排序

时间:2015-03-22 18:48:55

标签: json sorting swift

我想对从服务器上的JSON文件中读取的帖子进行排序。

我希望通过按下按钮排序,按名称或时间排序

我的代码

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 个答案:

答案 0 :(得分:1)

我们需要查看有关events数组结构的更多详细信息,但如果您要使用NSArray,那么您将使用其中一个NSArray排序方法。

首先,让我们假设JSON看起来像:

{
    "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"
        }
    ]
}

如果您想按名称排序,可以:

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

显然,如果日期采用可按字母顺序排序的形式,您可以执行上述操作。我选择了不易于排序的格式,以说明NSDateFormattersortedArrayUsingComparator

的更复杂组合
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()
    }
}