Address Book Tutorial in Swift and iOS

In this Address Book Tutorial for iOS, learn how to add, edit and display contacts in a fun app about pets. By Niv Yahel.

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Add a contact to group

The Address Book API allows you not only to store contacts but to add them to groups!. To start off, create the following method.

func createGroup(groupName: String) -> ABRecordRef {
  var groupRecord: ABRecordRef = ABGroupCreate().takeRetainedValue()

  let allGroups = ABAddressBookCopyArrayOfAllGroups(addressBookRef).takeRetainedValue() as Array
  for group in allGroups {
    let currentGroup: ABRecordRef = group
    let currentGroupName = ABRecordCopyValue(currentGroup, kABGroupNameProperty).takeRetainedValue() as! String
    if (currentGroupName == groupName) {
      println("Group exists")
      return currentGroup
    }
  }
  ABRecordSetValue(groupRecord, kABGroupNameProperty, groupName, nil)
  ABAddressBookAddRecord(addressBookRef, groupRecord, nil)
  saveAddressBookChanges()
  println("Made group")
  return groupRecord
}

This method takes a String as a parameter, searches through an array of all existing groups for if the requested group exists. If it already exists, it will return its ABRecordRef. If not, it will create a group with this name and save the changes.

Notice how ABRecordSetValue() and ABRecordCopyValue() apply to groups as well? Contacts and groups are both ABRecordRef types; the trick is simply to know which ABPropertyID you need to use.

Now that you have the group record, you’ll need to check if a contact already belongs to a group, add them if they aren’t, and save the changes. Add the following method:

func addPetToGroup(petContact: ABRecordRef) {
  // 1
  let groupName = "Animals"
  let group: ABRecordRef = createGroup(groupName)
  
  // 2
  if let groupMembersArray = ABGroupCopyArrayOfAllMembers(group) {
    let groupMembers = groupMembersArray.takeRetainedValue() as Array
    for member in groupMembers {
      let currentMember: ABRecordRef = member
      if currentMember === petContact {
        println("Already in it.")
        return
      }
    }
  }
  
  // 3
  let addedToGroup = ABGroupAddMember(group, petContact, nil)
  if !addedToGroup {
    println("Couldn't add pet to group.")
  }
  saveAddressBookChanges()
}

Here’s what’s going on in this method:

  1. First, you get a reference to the “Animals” group using createGroup(_:), which you just added.
  2. If there are group members already, you loop through the list to see if the current pet is already in the group. If so, you log out a message and return early from the method.
  3. Otherwise, you add the pet to the group and save the changes.

You want to give the user the option to add the pet to the group after the pet is in the address book. Find displayContactExistsAlert(_:) and add the following code just after you initialize contactExistsAlert:

contactExistsAlert.addAction(UIAlertAction(title: "Add to \"Animals\" Group", style: .Default, handler: { action in
  self.addPetToGroup(petRecord)
}))

Find addPetToContacts(_:) and add the following similar code just after you initialize contactAddedAlert:

contactAddedAlert.addAction(UIAlertAction(title: "Add to \"Animals\" Group", style: .Default, handler: { action in
  self.addPetToGroup(petRecord)
}))

This code adds an additional button to the alerts shown when you tap on a pet for adding the pet to the new group.

Build and run your app. You will now be able to add a Pet to a group after adding it for the first time and after every subsequent tap.

Bonus: Displaying Contact Records

The Address Book framework has a complementary framework called AddressBookUI, which provides UI elements much like those found in the Contacts app. ABPersonViewController is one of them, which allows you to present a contact’s information in a Contacts-like manner, allowing you to modify their information and even make phone calls.

Luckily, AddressBookUI contains UI components and is object-oriented so you won’t see any Core Foundation references here! :]

To begin, add the following import to the top of PetBookViewController.swift:

import AddressBookUI

Find displayContactExistsAlert(_:) and add the following code right after the line that initializes contactExistsAlert:

contactExistsAlert.addAction(UIAlertAction(title: "Show Contact", style: .Default, handler: { action in
  let personViewController = ABPersonViewController()
  personViewController.displayedPerson = petRecord
  self.navigationController?.pushViewController(personViewController, animated: true)
}))

That wasn’t so ruff. This action initializes a new ABPersonViewController object, which can display a single contact. You set the displayed record as the current pet record, and then push the view controller onto the navigation stack.

Build and run the app! Tap on a Pet that has already been added to your Address Book. You will now see “Show Contact” as an option. If you select that button, you’ll see the following:

PetBook-CheesyCatABPersonViewController

You can modify any information and even make calls from this screen! Sorry, that’s not actually Cheesy’s phone number – she’s very private in real life. :]

Where To Go From Here?

Here is the finished example project from this Address Book tutorial.

In this tutorial, you learned how to create a new record, add it to a group, and present it using ABPersonViewController. You can do many other cool things with the Address Book API, such as display and modify pre-existing contacts – why not give that a try as an extension of this tutorial?

The AddressBookUI framework has several more convenient classes other than ABPersonViewController for modifying the address book. You could almost re-build the entire Contacts app with these classes, which offers even more opportunity for your own address book apps!

If you have any questions or comments regarding this tutorial or the Address Book API, please join the discussion in the comments below!

Niv Yahel

Contributors

Niv Yahel

Author

Over 300 content creators. Join our team.