Swift 2.0 ContactsUI Framework

621 Views Asked by At

I am working on a project in Swift 2.0 that requires me to use the IOS 9s ContactUI Framework. The issue that I am having is properly picking a phone number from the contacts list. When I select a phone number from a contact, the application crashes.

Here is the code that I am using to perform this task.

var delegate: NewLocationViewControllerDelegate!
var contacts = [CNContact]()

override func viewDidLoad() {
    super.viewDidLoad()
    UIApplication.sharedApplication().delegate as! AppDelegate
    // Do any additional setup after loading the view.
}//end

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func openContacts(sender: UIButton) {
    let contactPicker = CNContactPickerViewController()
    contactPicker.delegate = self;
    contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey]

    self.presentViewController(contactPicker, animated: true, completion: nil)
}//end

func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {
    let contact = contactProperty.contact
    let phoneNumber = contactProperty.value as! CNPhoneNumber
    print(contact.givenName)
    print(phoneNumber.stringValue)
}//end
1

There are 1 best solutions below

1
On

The problem is that the tap on the phone number is trying to dial the phone - and on the simulator, there is no phone.

Your contactPicker:didSelectContactProperty: will never be called, because no phone number will ever be selected. Instead, tapping a phone number will try to dial that number. This is because you have not provided a predicateForSelectionOfProperty. You need to set the predicateForSelectionOfProperty to an NSPredicate that evaluates to true when the key is a phone number.