通过电话号码解析解析swift

通过电话号码解析解析swift,swift,parsing,contacts,Swift,Parsing,Contacts,在我的应用程序中,我保存用户给我的电话号码,以便其他人可以在应用程序中找到他们和他们的联系人。但我在解析电话号码时遇到困难,因为用户可以用不同的方式保存电话号码: –国家代码、区号、号码:+1(区号)xxx xxxx –国家代码,编号:+1 xxx xxxx –编号:xxx xxxx 我保存用户号码的方法是将区号和号码添加为一个长号码,然后分别保存国家代码。我试着通过分析从联系人中提取的电话号码来模拟我是如何保存这些号码的,但它不起作用。我有什么遗漏吗?我复制了底部的代码: if acc

在我的应用程序中,我保存用户给我的电话号码,以便其他人可以在应用程序中找到他们和他们的联系人。但我在解析电话号码时遇到困难,因为用户可以用不同的方式保存电话号码:

–国家代码、区号、号码:+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")
                    }
                }

请记住,全世界有数百种电话号码格式。不要假设典型的美国/加拿大电话号码。好吧,因为用户给你他们的号码,你可以有自己的数据库来核对其他人。我的意思是,你可以设置一个模式,比如国家代码+地区+号码。是的,你仍然无法100%使用用户的联系人,但使用你的应用程序的联系人将在那里。