As the title suggests, in my iOS app using swift I've got a CNContactProperty object and I want to extract the phone number from it as a string.
The CNContact property is returned from the standard CNContactPickerViewController via the delegate protocol function, after the user has selected a contact from it.
When a contact has multiple phone numbers, I want to be able to extract the one that the user tapped on in the contact view from the CNContactProperty.
I'm trying to do something like this:
let myString = theCNContactProperty.value as! String
However, this crashes with an (lldb) error. I suspect that maybe the "value" property is not what I need?
I'm able to retrieve arbitrary numbers like so:
let myString = contactProperty.contact.phoneNumbers[0].value.stringValue
Which returns the first number a contact has. However, this doesn't serve my purpose as I want to be able to extract the specific number selected by the user when a contact has more than 1 number.
I've been working on this for hours and can't figure it out, I'd appreciate any help you can give me!
Edit: This is NOT a duplicate of the provided link. The linked question is about retrieving all numbers from a contact, NOT a specifically selected one. There is a HUGE difference in that.
Correct Answer:
As Mahdi Moqadasi
wrote in the comments, the correct answer is to use (contactProperty.value as? CNPhoneNumber).stringValue
.
Or see the following answers:
Extract email from CNContactProperty - iOS 9
iOS Objective C: Get user selected phone number from CNContactProperty as a string