How to get a CNContact phone number(s) as string in Swift?

后端 未结 10 1792
执念已碎
执念已碎 2020-12-13 13:31

I am attempting to retrieve the names and phone number(s) of all contacts and put them into arrays with Swift in iOS. I have made it this far:



        
10条回答
  •  悲哀的现实
    2020-12-13 14:12

    Here's a Swift 5 solution.

    import Contacts
    
    func sendMessageTo(_ contact: CNContact) {
    
        let validTypes = [
            CNLabelPhoneNumberiPhone,
            CNLabelPhoneNumberMobile,
            CNLabelPhoneNumberMain
        ]
    
        let numbers = contact.phoneNumbers.compactMap { phoneNumber -> String? in
            guard let label = phoneNumber.label, validTypes.contains(label) else { return nil }
            return phoneNumber.value.stringValue
        }
    
        guard !numbers.isEmpty else { return }
    
        // process/use your numbers for this contact here
        DispatchQueue.main.async {
            self.sendSMSText(numbers)
        }
    }
    

    You can find available values for the validTypes array in the CNPhoneNumber header file.

    They are:

    CNLabelPhoneNumberiPhone
    CNLabelPhoneNumberMobile
    CNLabelPhoneNumberMain
    CNLabelPhoneNumberHomeFax
    CNLabelPhoneNumberWorkFax
    CNLabelPhoneNumberOtherFax
    CNLabelPhoneNumberPager
    

提交回复
热议问题