iosswiftcontactpickercncontactpicker

CNContactPickerViewController validation for mobile number in iOS Swift


I have used CNContactPickerViewController to enable user to pick a contact from their contact list stored on the phone. I use the contact name and number using CNContactPicker delegate methods. Code as below

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
    // You can fetch selected name and number in the following way

    // user name
    let userName: String = "\(contact.givenName) \(contact.familyName)"

    // user phone number
    let userPhoneNumbers:[CNLabeledValue<CNPhoneNumber>] = contact.phoneNumbers
    let firstPhoneNumber:CNPhoneNumber = userPhoneNumbers[0].value

    // user phone number string
    let primaryPhoneNumberStr:String = firstPhoneNumber.stringValue

   // print(primaryPhoneNumberStr)

    textfieldName.text = userName
    textfieldContactNo.text = primaryPhoneNumberStr
}

I would like to apply validations following validations to it -

  1. Selected no is a mobile phone or landline number.

  2. Check if the number has a country code.

Can someone please help me with the above validations.


Solution

  • This is a tricky question that I believe there is no correct && valid single answer :) I'll explain why.

    Let's take your first validation, which you want to identify the user selected contact's phone number is a mobile phone or landline. At present, iOS is not providing an option call landline. The existing options are like below.

    enter image description here

    As you can see in the above image, you can get the phone number is added to any of the above category. How you can achieve that from code is as below.

    let phoneNumberType = userPhoneNumbers[0].label
    

    With a switch or if-else statement, you can filter the category. As an example

        if (phoneNumberType?.contains("Mobile"))! {
            print("This is a mobile number")
        }
    

    The second validation that you are asking is to check whether the number has a country code. Look at the following debug output.

    enter image description here

    As you can see, even though the real phone number has a country code of New Zealand, the countryCode key gives a different one, which I am not sure why. You can extract the phone number and create your own validations (Ex. +, 00 ...) but there are several combinations that you need to consider.

    After all these effort, if you are uploading your build to App store, there is possibility of getting rejected (unless you have a valid arguments) since you are trying to extract user's personal information. That's why my very first sentence is valid ;)