user7077886 user7077886 - 15 days ago 4
iOS Question

swift: Alphabetiz data being parsed from a JSON

I wrote my own function in Swift2 to parse a JSON. Once the JSON is parsed, a list of data that was pulled from the JSON is displayed in a

tableView
on my app. I am trying to figure out how to display this data in alphabetical order. I think this needs to happen somewhere before the append method I call in the function. I would imagine this needs to be a
sort
function but I have not been able to figure out the correct sort function in Swift2 that will execute this properly. Any help I can get is appreciated!
Here is my parseJSON function:

func parseJSON(){
do{
let data = NSData(contentsOfURL: NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!)

let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

for anItem in jsonResult as! [Dictionary<String, AnyObject>]{

let mifiName2 = anItem["name"] as! String
let mifiId = anItem["employeeId"] as! Int

let newName = Name(mifiName: mifiName2, mifiId: mifiId)
nameOfMifi.append(newName)
//print("Name: \(newName)")

}
}
catch let error as NSError{
print(error.debugDescription)
}
}

Answer

You need to sort your array after all the object is append in Array means after the for loop.

for anItem in jsonResult as! [Dictionary<String, AnyObject>]{

    let mifiName2 = anItem["name"] as! String
    let mifiId = anItem["employeeId"] as! Int

    let newName = Name(mifiName: mifiName2, mifiId: mifiId)
    nameOfMifi.append(newName)
    //print("Name: \(newName)")
}

//Now you need to sort your array on the basis of name like this
nameOfMifi.sortInPlace { $0.mifiName < $1.mifiName } 

Edit: As @vadian suggested do not use NSData(contentsOfURL:) because it will block your UI, so batter to use NSURLSession like this.

let session = NSURLSession.sharedSession()
let url = NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!
var task = session.dataTaskWithURL(url, completionHandler: {
    (data, response, error) -> Void in
    if error != nil {
        return
    }

    if let jsonResult = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [Dictionary<String, AnyObject>] {

        for anItem in jsonResult {

            let mifiName2 = anItem["name"] as! String
            let mifiId = anItem["employeeId"] as! Int

            let newName = Name(mifiName: mifiName2, mifiId: mifiId)
            nameOfMifi.append(newName)
            //print("Name: \(newName)")
        }
        //Now you need to sort your array on the basis of name like this
        nameOfMifi.sortInPlace { $0.mifiName < $1.mifiName } 

        //Now reload tableView on main thread.
        dispatch_async(dispatch_get_main_queue()) {
             self.tableView.reloadData()
        }
    }
})
task.resume()