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

后端 未结 10 1782
执念已碎
执念已碎 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:06

    Swift 3 "_$!<Mobile>!$_" This item is written to create difference as well as putting a piece of opportunity to rely on various options.

    for con in contacts
    {
        for num in con.phoneNumbers
        {
            if num.label == "_$!<Mobile>!$_"    //Please Don't Change this!
            {
                self.contactNames.append(con.givenName)
                self.contactNums.append(num.value.stringValue)
                break
            }
            else
            {
                continue
            }
        }
    }
    

    Here we have num.value.stringValue

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-13 14:12

    Keeping things simple:

    let phoneNumbers: [String] = contact.phoneNumbers.compactMap { (phoneNumber: CNLabeledValue) in
        guard let number = phoneNumber.value.value(forKey: "digits") as? String else { return nil }
        return number
    }
    
    0 讨论(0)
  • 2020-12-13 14:18

    I found the solution: (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String

    0 讨论(0)
提交回复
热议问题