У меня есть приложение, в котором у меня есть кнопка, текст заголовка которой отображает название страны и код при нажатии на нее. то есть отображается IN +91. при нажатии кнопки открывается всплывающее окно, в котором перечислены все страны с названием и кодом страны. Теперь, кроме этого, у меня есть текстовое поле номера мобильного телефона, которое будет отображать номер мобильного телефона при выборе из списка контактов. Рядом с мобильным текстовым полем у меня есть кнопка, которая открывает список контактов по умолчанию, теперь, что я хочу, скажем, я выбрал контакт, номер которого +919998536042, тогда номер 9998536042 должен отображаться в текстовом поле, а текст заголовка кнопки должен отображать IN + 91. то есть расширение из списка контактов должно совпадать с кодом страны в массиве списков стран, который я использовал для отображения списка стран. Пожалуйста, помогите мне. Я застрял. и еще одна вещь, скажем, я нажал на кнопку In +91 и выбрал, например, US +1, затем я выбрал контакт, который не имеет расширения, тогда текст заголовка кнопки останется таким же, как US +1, и если расширение найдено для пример +91, затем какое-то число, затем текст заголовка кнопки будет IN + 91
изображения моего приложения для лучшего понимания:
, теперь нажимая IN +91, открывается вверх выбора, показанного на скриншоте 2
данные страны:
let Country:[[String:[String]]] = [["AF": ["Afghanistan","93"]],
["AX": ["Aland Islands","358"]],
["AL": ["Albania","355"]],
["DZ": ["Algeria","213"]],
["AS": ["American Samoa","1"]],
["AD": ["Andorra","376"]],
["AO": ["Angola","244"]],
["AI": ["Anguilla","1"]],
["AQ": ["Antarctica","672"]],
["AG": ["Antigua and Barbuda","1"]],
["AR": ["Argentina","54"]],
["AM": ["Armenia","374"]],
["AW": ["Aruba","297"]],
["AU": ["Australia","61"]],
["AT": ["Austria","43"]],
["AZ": ["Azerbaijan","994"]],
["BS": ["Bahamas","1"]],
["BH": ["Bahrain","973"]],
["BD": ["Bangladesh","880"]],
["BB": ["Barbados","1"]],
["BY": ["Belarus","375"]],
["BE": ["Belgium","32"]],
["BZ": ["Belize","501"]],
["BJ": ["Benin","229"]],
["BM": ["Bermuda","1"]],
["BT": ["Bhutan","975"]],
["BO": ["Bolivia","591"]],
["BA": ["Bosnia and Herzegovina","387"]],
["BW": ["Botswana","267"]],
["BV": ["Bouvet Island","47"]],
["BQ": ["BQ","599"]],
["BR": ["Brazil","55"]],
["IO": ["British Indian Ocean Territory","246"]],
["VG": ["British Virgin Islands","1"]],
["BN": ["Brunei Darussalam","673"]],
["BG": ["Bulgaria","359"]],
["BF": ["Burkina Faso","226"]],
["BI": ["Burundi","257"]],
["KH": ["Cambodia","855"]],
["CM": ["Cameroon","237"]],
["CA": ["Canada","1"]],
["CV": ["Cape Verde","238"]],
["KY": ["Cayman Islands","345"]],
["CF": ["Central African Republic","236"]],
["TD": ["Chad","235"]],
["CL": ["Chile","56"]],
["CN": ["China","86"]],
["CX": ["Christmas Island","61"]],
["CC": ["Cocos (Keeling) Islands","61"]],
["CO": ["Colombia","57"]],
["KM": ["Comoros","269"]],
["CG": ["Congo (Brazzaville)","242"]],
["CD": ["Congo, Democratic Republic of the","243"]],
["CK": ["Cook Islands","682"]],
["CR": ["Costa Rica","506"]],
["CI": ["Côte d'Ivoire","225"]],
["HR": ["Croatia","385"]],
["CU": ["Cuba","53"]],
["CW": ["Curacao","599"]],
["CY": ["Cyprus","537"]],
["CZ": ["Czech Republic","420"]],
["DK": ["Denmark","45"]],
["DJ": ["Djibouti","253"]],
["DM": ["Dominica","1"]],
["DO": ["Dominican Republic","1"]],
["EC": ["Ecuador","593"]],
["EG": ["Egypt","20"]],
["SV": ["El Salvador","503"]],
["GQ": ["Equatorial Guinea","240"]],
["ER": ["Eritrea","291"]],
["EE": ["Estonia","372"]],
["ET": ["Ethiopia","251"]],
["FK": ["Falkland Islands (Malvinas)","500"]],
["FO": ["Faroe Islands","298"]],
["FJ": ["Fiji","679"]],
["FI": ["Finland","358"]],
["FR": ["France","33"]],
["GF": ["French Guiana","594"]],
["PF": ["French Polynesia","689"]],
["TF": ["French Southern Territories","689"]],
["GA": ["Gabon","241"]],
["GM": ["Gambia","220"]],
["GE": ["Georgia","995"]],
["DE": ["Germany","49"]],
["GH": ["Ghana","233"]],
["GI": ["Gibraltar","350"]],
["GR": ["Greece","30"]],
["GL": ["Greenland","299"]],
["GD": ["Grenada","1"]],
["GP": ["Guadeloupe","590"]],
["GU": ["Guam","1"]],
["GT": ["Guatemala","502"]],
["GG": ["Guernsey","44"]],
["GN": ["Guinea","224"]],
["GW": ["Guinea-Bissau","245"]],
["GY": ["Guyana","595"]],
["HT": ["Haiti","509"]],
["VA": ["Holy See (Vatican City State)","379"]],
["HN": ["Honduras","504"]],
["HK": ["Hong Kong, Special Administrative Region of China","852"]],
["HU": ["Hungary","36"]],
["IS": ["Iceland","354"]],
["IN": ["India","91"]],
["ID": ["Indonesia","62"]],
["IR": ["Iran, Islamic Republic of","98"]],
["IQ": ["Iraq","964"]],
["IE": ["Ireland","353"]],
["IM": ["Isle of Man","44"]],
["IL": ["Israel","972"]],
["IT": ["Italy","39"]],
["JM": ["Jamaica","1"]],
["JP": ["Japan","81"]],
["JE": ["Jersey","44"]],
["JO": ["Jordan","962"]],
["KZ": ["Kazakhstan","77"]],
["KE": ["Kenya","254"]],
["KI": ["Kiribati","686"]],
["KP": ["Korea, Democratic People's Republic of","850"]],
["KR": ["Korea, Republic of","82"]],
["KW": ["Kuwait","965"]],
["KG": ["Kyrgyzstan","996"]],
["LA": ["Lao PDR","856"]],
["LV": ["Latvia","371"]],
["LB": ["Lebanon","961"]],
["LS": ["Lesotho","266"]],
["LR": ["Liberia","231"]],
["LY": ["Libya","218"]],
["LI": ["Liechtenstein","423"]],
["LT": ["Lithuania","370"]],
["LU": ["Luxembourg","352"]],
["MO": ["Macao, Special Administrative Region of China","853"]],
["MK": ["Macedonia, Republic of","389"]],
["MG": ["Madagascar","261"]],
["MW": ["Malawi","265"]],
["MY": ["Malaysia","60"]],
["MV": ["Maldives","960"]],
["ML": ["Mali","223"]],
["MT": ["Malta","356"]],
[ "MH": ["Marshall Islands","692"]],
["MQ": ["Martinique","596"]],
[ "MR": ["Mauritania","222"]],
["MU": ["Mauritius","230"]],
[ "YT": ["Mayotte","262"]],
["MX": ["Mexico","52"]],
[ "FM": ["Micronesia, Federated States of","691"]],
["MD": ["Moldova","373"]],
[ "MC": ["Monaco","377"]],
["MN": ["Mongolia","976"]],
[ "ME": ["Montenegro","382"]],
["MS": ["Montserrat","1"]],
[ "MA": ["Morocco","212"]],
["MZ": ["Mozambique","258"]],
[ "MM": ["Myanmar","95"]],
["NA": ["Namibia","264"]],
[ "NR": ["Nauru","674"]],
["NP": ["Nepal","977"]],
[ "NL": ["Netherlands","31"]],
["AN": ["Netherlands Antilles","599"]],
[ "NC": ["New Caledonia","687"]],
["NZ": ["New Zealand","64"]],
[ "NI": ["Nicaragua","505"]],
["NE": ["Niger","227"]],
[ "NG": ["Nigeria","234"]],
["NU": ["Niue","683"]],
[ "NF": ["Norfolk Island","672"]],
["MP": ["Northern Mariana Islands","1"]],
[ "NO": ["Norway","47"]],
["OM": ["Oman","968"]],
[ "PK": ["Pakistan","92"]],
["PW": ["Palau","680"]],
[ "PS": ["Palestinian Territory, Occupied","970"]],
["PA": ["Panama","507"]],
[ "PG": ["Papua New Guinea","675"]],
["PY": ["Paraguay","595"]],
[ "PE": ["Peru","51"]],
["PH": ["Philippines","63"]],
[ "PN": ["Pitcairn","872"]],
["PL": ["Poland","48"]],
[ "PT": ["Portugal","351"]],
["PR": ["Puerto Rico","1"]],
[ "QA": ["Qatar","974"]],
["RE": ["Réunion","262"]],
[ "RO": ["Romania","40"]],
["RU": ["Russian Federation","7"]],
[ "RW": ["Rwanda","250"]],
["SH": ["Saint Helena","290"]],
[ "KN": ["Saint Kitts and Nevis","1"]],
["LC": ["Saint Lucia","1"]],
["PM": ["Saint Pierre and Miquelon","508"]],
[ "VC": ["Saint Vincent and Grenadines","1"]],
["BL": ["Saint-Barthélemy","590"]],
["MF": ["Saint-Martin (French part)","590"]],
[ "WS": ["Samoa","685"]],
["SM": ["San Marino","378"]],
[ "ST": ["Sao Tome and Principe","239"]],
["SA": ["Saudi Arabia","966"]],
[ "SN": ["Senegal","221"]],
["RS": ["Serbia","381"]],
[ "SC": ["Seychelles","248"]],
["SL": ["Sierra Leone","232"]],
["SG": ["Singapore","65"]],
[ "SX": ["Sint Maarten","1"]],
["SK": ["Slovakia","421"]],
[ "SI": ["Slovenia","386"]],
["SB": ["Solomon Islands","677"]],
[ "SO": ["Somalia","252"]],
["ZA": ["South Africa","27"]],
[ "GS": ["South Georgia and the South Sandwich Islands","500"]],
["SS": ["South Sudan","211"]],
[ "ES": ["Spain","34"]],
["LK": ["Sri Lanka","94"]],
[ "SD": ["Sudan","249"]],
[ "SR": ["Suriname","597"]],
["SJ": ["Svalbard and Jan Mayen Islands","47"]],
[ "SZ": ["Swaziland","268"]],
[ "SE": ["Sweden","46"]],
[ "CH": ["Switzerland","41"]],
[ "SY": ["Syrian Arab Republic (Syria)","963"]],
[ "TW": ["Taiwan, Republic of China","886"]],
["TJ": ["Tajikistan","992"]],
[ "TZ": ["Tanzania, United Republic of","255"]],
["TH": ["Thailand","66"]],
[ "TL": ["Timor-Leste","670"]],
[ "TG": ["Togo","228"]],
["TK": ["Tokelau","690"]],
["TO": ["Tonga","676"]],
[ "TT": ["Trinidad and Tobago","1"]],
[ "TN": ["Tunisia","216"]],
[ "TR": ["Turkey","90"]],
[ "TM": ["Turkmenistan","993"]],
[ "TC": ["Turks and Caicos Islands","1"]],
[ "TV": ["Tuvalu","688"]],
["UG": ["Uganda","256"]],
[ "UA": ["Ukraine","380"]],
[ "AE": ["United Arab Emirates","971"]],
["GB": ["United Kingdom","44"]],
["US": ["United States of America","1"]],
["UY": ["Uruguay","598"]],
["UZ": ["Uzbekistan","998"]],
["VU": ["Vanuatu","678"]],
["VE": ["Venezuela (Bolivarian Republic of)","58"]],
["VN": ["Viet Nam","84"]],
["VI": ["Virgin Islands, US","1"]],
["WF": ["Wallis and Futuna Islands","681"]],
["EH": ["Western Sahara","212"]],
["YE": ["Yemen","967"]],
["ZM": ["Zambia","260"]],
["ZW": ["Zimbabwe","263"]]
]
Мой код для списка стран:
//Variables country popup
var key = [String]()
var value: NSMutableArray = NSMutableArray()
var c_name = [String]()
var c_code = [String]()
var searchTag = String()
var select_code = String()
var select_c_s_name = String()
override func viewDidLoad()
{
super.viewDidLoad()
get_country_data()
}
//MARK:- Fetch Country Data
func get_country_data()
{
key.removeAll()
value.removeAllObjects()
for i in 0 ..< Country.count
{
let U = [String](Country[i].keys)
let V = Array(Country[i][U[0]]!)
key.append(U[0])
value.add(V)
}
c_name.removeAll()
c_code.removeAll()
for j in 0 ..< value.count
{
c_name.append((value.object(at: j) as! NSArray).object(at: 0) as! String)
c_code.append((value.object(at: j) as! NSArray).object(at: 1) as! String)
}
self.cntryTblView.reloadData()
}
//MARK:- Country Code Search Functions
func search_data()
{
let searchResult = Country.flatMap({ $0 }).filter {
let variable = $0
return variable.value[0].lowercased().contains(searchTag) || variable.value[1].lowercased().contains(searchTag) || variable.key.lowercased().contains(searchTag)
}
key.removeAll()
value.removeAllObjects()
for i in 0..<searchResult.count
{
key.append(searchResult[i].key)
value.add(searchResult[i].value)
}
c_name.removeAll()
c_code.removeAll()
for j in 0..<value.count {
c_name.append((value.object(at: j) as! NSArray).object(at: 0) as! String)
c_code.append((value.object(at: j) as! NSArray).object(at: 1) as! String)
}
self.cntryTblView.reloadData()
}
@IBAction func selectCntryCode(_ sender: DCustomButton)
{
ApiUtillity.sharedInstance.AddSubViewtoParentView(parentview: self.view, subview: self.cntryPopupView)
}
extension NeighbourDetailsVC: UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return key.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "CountryCodeCell", for: indexPath) as! CountryCodeCell
cell.cntry_img.image = UIImage(named: key[indexPath.row])
cell.cntry_code.text = "+"+c_code[indexPath.row]
cell.cntry_name.text = c_name[indexPath.row]+" "+"("+key[indexPath.row]+")"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
select_code = c_code[indexPath.row]
select_c_s_name = key[indexPath.row]
self.cntryTblView.reloadData()
self.countryCodeBtn.setTitle(select_c_s_name+" +"+select_code, for: .normal)
self.get_country_data()
}
}
Код для при нажатии на кнопку, которая открывает сборщик списка контактов:
//MARK:- Open Contact Picker
@IBAction func openContactPicker(_ sender: UIButton)
{
askForContactAccess()
}
//MARK:- Ask for contact access
func askForContactAccess()
{
let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
switch authorizationStatus
{
case .denied, .notDetermined:
self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
if !access {
if authorizationStatus == CNAuthorizationStatus.denied {
DispatchQueue.main.async {
let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
let alertController = UIAlertController(title: "Contacts", message: message, preferredStyle: UIAlertController.Style.alert)
let dismissAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { (action) -> Void in
}
alertController.addAction(dismissAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
})
break
case .authorized:
contactPicker.delegate = self
contactPicker.displayedPropertyKeys = [CNContactGivenNameKey, CNContactMiddleNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
self.present(contactPicker, animated: true)
break
default:
break
}
}
// Delegate method for contact picker in which i am setting selected contact name and number to name and mobile textfield
extension NeighbourDetailsVC: CNContactPickerDelegate
{
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact)
{
let phoneNumbersCount = contact.phoneNumbers.count
let userName: String = "\(contact.givenName) \(contact.middleName) \(contact.familyName)"
guard phoneNumbersCount > 0 else
{
let alertController = UIAlertController(title: "Selected contact doesn't have a number", message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: {
alert -> Void in
})
alertController.addAction(cancelAction)
dismiss(animated: true)
self.present(alertController, animated: true, completion: nil)
return
}
if phoneNumbersCount == 1
{
setNumberFromContact(contactNumber: contact.phoneNumbers[0].value.stringValue)
self.nameTxtField.text = userName
}
else
{
let alertController = UIAlertController(title: "Select one of the numbers", message: nil, preferredStyle: .alert)
for i in 0...phoneNumbersCount-1
{
let phoneAction = UIAlertAction(title: contact.phoneNumbers[i].value.stringValue, style: .default, handler: {
alert -> Void in
self.setNumberFromContact(contactNumber: contact.phoneNumbers[i].value.stringValue)
self.nameTxtField.text = userName
})
alertController.addAction(phoneAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: {
alert -> Void in
})
alertController.addAction(cancelAction)
dismiss(animated: true)
self.present(alertController, animated: true, completion: nil)
}
}
func setNumberFromContact(contactNumber: String)
{
var contactNumber = contactNumber.replacingOccurrences(of: "-", with: "")
contactNumber = contactNumber.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "")
contactNumber = contactNumber.replacingOccurrences(of: " ", with: "")
guard contactNumber.count >= 10 else
{
let alertController = UIAlertController(title: "Selected contact doesn't have a valid number", message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: {
alert -> Void in
})
alertController.addAction(cancelAction)
dismiss(animated: true)
self.present(alertController, animated: true, completion: nil)
return
}
self.mobileTxtField.text = String(contactNumber.suffix(10))
self.mobileTxtField.resignFirstResponder()
}
}