通过电话号码解析快速解析

时间:2018-06-24 21:17:29

标签: swift parsing contacts

在我的应用程序中,我保存了他们给我的用户电话号码,以便其他人可以找到他们,并可以在应用程序中找到他们的联系人。但是我无法解析电话号码,因为用户可以用不同的方式保存电话号码:

–国家/地区代码,区号,数字:+1(区号)xxx-xxxx

–国家/地区代码,数字:+1 xxx-xxxx

–数字:xxx-xxxx

我保存用户号码的方法是将区号和号码添加为一个长号,然后分别保存国家/地区代码。我尝试解析“联系人”中的电话号码,以模仿我如何保存电话号码,但是它不起作用。我有什么想念的吗?我已经在底部复制了代码:

    if accessGranted {
                    let contactStore = CNContactStore()
                    let keys = [CNContactPhoneNumbersKey]
                    let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
                    do {
                        try contactStore.enumerateContacts(with: request, usingBlock: { (contact, error) in
                            let phoneNumberRaw = contact.phoneNumbers.first?.value.stringValue ?? ""

                            var phoneNumberRawArray = phoneNumberRaw.components(separatedBy: " ")
                            var phoneString = ""
                            if phoneNumberRawArray.count >= 3 { //probably has country code in the front
                                //remove country code
                                phoneNumberRawArray.removeFirst()
                            }

                            //add to phone string
                            for phone in phoneNumberRawArray {
                                phoneString.append(phone)
                            }
                            phoneString = phoneString.replacingOccurrences(of: "(", with: "")
                            phoneString = phoneString.replacingOccurrences(of: " ", with: "")
                            phoneString = phoneString.replacingOccurrences(of: ")", with: "")
                            phoneString = phoneString.replacingOccurrences(of: "-", with: "")



                             self.contactsPhoneNumbers.append(phoneString)    

                                //get country code
                                for ContactNumber:CNLabeledValue in contact.phoneNumbers
                            {
                                let fullNumber  = ContactNumber.value
                                let countryCode = fullNumber.value(forKey: "countryCode") as? String
                                self.contactsCountryCode.append(countryCode!)
                            }

                        })
                    }
                    catch {
                        print("Unable to get contacts")
                    }
                }

0 个答案:

没有答案