It’s time to learn Swift. After Swift first release in 2014, now more and more people start using Swift as their program language in iOS. Therefore, I decide to use Swift in my current project, loading people first name, last name and phone number from contact. This will be a good project to learn Swift from beginning.

When we create new project in Xcode, it will use Swift language by default. The only different between Objective-c and Swift is there is no .h and .m file any more. There is only one .swift file which we can declare class inside. In my new project, there is only two .swift file. One is AppDelegate.swift; the other one is ViewController.swift. All my logic to get people information from contact are in ViewController.swift. Now, I will start to show you how to get people first name, last name, and phone number from contact. All example source code will use swift.

Swift Project Folder

Get People Contact Information from Contact

This is very simple project. So it is very good to be used to study a new language. To open contact view and handle the user selection, we need to implement ABPeoplePickerNavigationControllerDelegate and UINavigationControllerDelegate delegates. A little bit different, we will implement delegate in Swift in following way:

class ViewController: UIViewController, ABPeoplePickerNavigationControllerDelegate, UINavigationControllerDelegate {
//class content
}

Following source code will open the contact view and let user select people information from contact. The source code will be implemented by Swift.

    @IBAction func OpenContactView(sender: UIButton) {
        self.presentViewController(self.peopleSelector, animated: true, completion: nil);
    }

After user select a people in the contact view?peoplePickerNavigationController function of ABPeoplePickerNavigationControllerDelegate delegate will be called. Here is the Swift example source code.

func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
        peoplePicker.dismissViewControllerAnimated(true, completion: nil);
        
        let index = 0 as CFIndex;
        
        //Get Name
        var firstName:String?;
        let firstNameObj = ABRecordCopyValue(person, kABPersonFirstNameProperty);
        if(firstNameObj != nil) {
            firstName = firstNameObj.takeRetainedValue() as? String;
        } else {
            firstName = "";
        }
        
        var lastName:String?;
        let lastNameObj = ABRecordCopyValue(person, kABPersonLastNameProperty);
        if(lastNameObj != nil) {
            lastName = lastNameObj.takeRetainedValue() as? String;
        } else {
            lastName = "";
        }
        
        //Get Phone Number
        var phoneNumber:String?;
        let unmanagedPhones:Unmanaged? = ABRecordCopyValue(person, kABPersonPhoneProperty);
        if(unmanagedPhones != nil) {
            let phoneNumbers = unmanagedPhones?.takeRetainedValue();
            if(ABMultiValueGetCount(phoneNumbers) > 0) {
                phoneNumber = ABMultiValueCopyValueAtIndex(phoneNumbers, index).takeRetainedValue() as? String;
                phoneNumber = "Phone Number is empty!";
            } else {
                phoneNumber = "Phone Number is empty!";
            }
        
            self.phoneLabel.text = phoneNumber;
        }
    }

Though the example is quite simple, but it covers lots of basic Swift features. You can find more learning points in this article: Swift or Objective-C Which One Shall I Choose?. Here I will only make following two point more clear:

Question Mark in Swift

What the meaning of question mark ‘?’ in swift? You can find lots of questions like this. “?” will wrap the variable to be an optional type. Here is an example:

var myStr:String?

The question mark will indicate the variable myStr could be a String or nil. So the following code will give an error:

Value of optional type “String?” not unwrapped; Do you mean to use “!” or “?”

var myStrI:String?
var myStrII:String = myStrI;

Here are two solutions for this problem. One is declaring your variable as optional String as well. For example:

var myStrI:String?
var myStrII:String? = myStrI;

Another solution is use exclamation mark in Swift. So what the meaning of exclamation mark ‘!’ in swift?

Exclamation Mark in Swift

This is another special usage of “!” in Swift. When it comes with variable, it will unwrap an optional type variable. For example:

var myStrI:String?
var myStrII:String = myStrI!;

In this way, exclamation mark will unwrap the variable myStrI from optional String type to String type. However, you must make sure the variable myStrI not to be nil, otherwise it will cause another problem:

fatal error: unexpectedly found nil while unwrapping an Optional value

Get Full Source Code under $1.99


You will be able to get the full source code under $1.99. You will have the full permission to use it, modify it or publish it in any projects.

Previous PostNext Post

11 Comments

  1. can u please give me that code in which i can get all contacts of my contact book and then can select some contacts and then can display them also in other page. please

    1. HII Hina.

      i have the same problem. I displayed the contacts and selected but it didn’t display in another page. did you get solution for that. if you know the answer please tell me. Thank you

  2. Hello, I bought the code but I am getting this error when I run the code as is:

    Terminating app due to uncaught exception ‘CNPropertyNotFetchedException’, reason: ‘A property was not requested when contact was fetched.’

    1. Can you please check what the ios version you are using. As I know, in iOS 10, there is a big change on “Address Book API”. Therefore, now you need to check your iOS version. If it is iOS9 or 10, then you can use “Contacts” framework. If it is iOS8, you need to use the Address Book.

    2. Can you please check what the ios version you are using. As I know, in iOS 10, there is a big change on “Address Book API”. Therefore, now you need to check your iOS version. If it is iOS9 or 10, then you can use “Contacts” framework. If it is iOS8, you need to use the Address Book.

Leave a Reply

Your email address will not be published. Required fields are marked *