Search code examples
iosswiftcncontact

Fetching contact no crashes when there is no phone no assigned to the contact


I am trying to read the contact phone no. The below code works fine if the number is available but if there are no phone no assigned to the contact , it is crashing. Can Anu let me know how to handle this.

((currentContact.phoneNumbers.first?.value)! as CNPhoneNumber).stringValue

Solution

  • You should learn about optional values in Swift...

    if let contactPhoneNumber = currentContact.phoneNumbers.first?.value?.stringValue {
        // do something with the value
    } 
    else {
        // the value isn't there 
    }