Jeesson_7
Jeesson_7

Reputation: 811

How do we get phone number from contacts using swift in Iphone app?

I have an app which have button named "contacts". I have to access my phone contacts when I click it.Also i have to get the phone no from the selected contact. Can anyone please suggest a working code?

Upvotes: 1

Views: 247

Answers (1)

Jeesson_7
Jeesson_7

Reputation: 811

I got it anyway. Here is how i did it

//class content

class ViewController: UIViewController, ABPeoplePickerNavigationControllerDelegate, UINavigationControllerDelegate

Following source code will open the contact view and let user select people information from contact.

@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;

        }

    }

Upvotes: 1

Related Questions