0

I have small problem in load phone contacts in view controller, i successfully loaded my phone contacts in Tableview with names and number, but it the contacts loading names as randomly, i want contact name must be alphabetic order which equal to number

Here is my sample code:

func contactDetail () {

    var myPhValue:NSString!
    var myPBfirstname:NSString!

    let qualityOfServiceClass = QOS_CLASS_BACKGROUND
    let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
    dispatch_async(backgroundQueue,  {
        let addressBook : ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
        ABAddressBookRequestAccessWithCompletion(addressBook, { (granted : Bool, error: CFError!) -> Void in
            if granted == true {
                let allContacts : NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue()
                for contactRef:ABRecordRef in allContacts { // first name
                    myPBfirstname = ABRecordCopyValue(contactRef, kABPersonFirstNameProperty)?.takeRetainedValue() as! NSString? ?? ""
                    let myPBlastname = ABRecordCopyValue(contactRef, kABPersonLastNameProperty)?.takeRetainedValue() as! NSString? ?? ""
                    let phonesRef: ABMultiValueRef = ABRecordCopyValue(contactRef, kABPersonPhoneProperty)?.takeRetainedValue() as ABMultiValueRef? ?? ""
                    var phonesArray  = Array<Dictionary<String,String>>()
                    for var i:Int = 0; i < ABMultiValueGetCount(phonesRef); i++ {
                        let myPhLabel = ABMultiValueCopyLabelAtIndex(phonesRef, i)?.takeRetainedValue() as NSString? ?? ""
                        myPhValue = ABMultiValueCopyValueAtIndex(phonesRef, i)?.takeRetainedValue() as! NSString? ?? ""
                        if myPhLabel.containsString("Mobile") {

                        }
                    }
                    let nameString = " "+(myPBlastname as String)
                    let nameValues = (myPBfirstname as String)+(nameString as String)
                    let contactDict : Dictionary = ["name": nameValues,"phone":myPhValue]
                    self.contactArray.addObject(contactDict)

                    if self.contactArray.count == 0 {
                        NSLog("contactValue is Zero")
                    }
                    else{
                        NSLog("count Value %d", self.contactArray.count)
                    }

                }


            }

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                self.contactTable.hidden = false
                self.contactTable.reloadData()


            })
        })
    })

}



func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
 return contactArray.count
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
     let cell:UITableViewCell = self.contactTable.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
    cell.selectionStyle = UITableViewCellSelectionStyle.None

    cell.preservesSuperviewLayoutMargins = false
    cell.separatorInset = UIEdgeInsetsZero
    cell.layoutMargins = UIEdgeInsetsZero



    cell.textLabel!.text = contactArray.valueForKey("name").objectAtIndex(indexPath.row) as? String

    return cell

}
naktinis
  • 3,957
  • 3
  • 36
  • 52
user3458924
  • 105
  • 5
  • 18

3 Answers3

3

You can use:

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
var sortedResults: NSArray = contactArray.sortedArrayUsingDescriptors([descriptor])
Patrick
  • 1,629
  • 5
  • 23
  • 44
3

As I assume from your code your contactArray is set up with values like this:

let contactArray = [["name": "tim", "phone": 123], ["name": "adi", "phone": 1234], ["name": "cora", "phone": 456], ["name": "berta", "phone": 678]]

To sort it by the names you can use the sort method:

let sortedContactArray = contactArray.sort{ ($0["name"] as! String) < ($1["name"] as! String) }

// result: [["phone": 1234, "name": adi], ["phone": 678, "name": berta], ["phone": 456, "name": cora], ["phone": 123, "name": tim]]
ronatory
  • 7,156
  • 4
  • 29
  • 49
  • 1
    Is it possible to categorise them alphabetically such that we can list them in tableview sections? – Satyam Mar 13 '17 at 07:19
  • I don't understand what you mean by `categorize them alphabetically`? Can you give a specific example or explain your question more in detail? @Satyam – ronatory Mar 13 '17 at 21:06
2

Also you can youse concise Swifty way of sorting away (of course if you are using Swift Array instead of NSArray)

contactArray.sortInPlace { $0["name"] < $1["name"] }
Peter K
  • 438
  • 3
  • 10