Poles Poles - 4 months ago 54
iOS Question

Fetch localized phone label using Contacts frameworks

I'm trying to fetch localized phone label value using CNContact.My attampt so far:

NSError *error = nil;

CNContactFetchRequest *fetchRequest =[[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];

[addressBook enumerateContactsWithFetchRequest:fetchRequest error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

CNLabeledValue *phoneNumberValue = contact.phoneNumbers.firstObject;

NSString *label = phoneNumberValue.label;
NSLog(@"Phone Label: %@",label); //Logs value like _$!<Home>!$_

CNPhoneNumber *phoneNumber = phoneNumberValue.value;
NSString *phoneNumberString = phoneNumber.stringValue;

NSLog(@"Phone No: %@",phoneNumberString);
}];


The problem is the phone label returns raw value like
_$!<Home>!$_
,
_$!<Mobile>!$_
. But I need Plain text like Home, Mobile. Is there any way I can get the localized value using Contact frameworks. I don't want to use Addressbook as it is deprecated in iOS 9.

Answer

use CNLabeledValues class method + localizedStringForLabel: and pass the label

example:

   CNLabeledValue *phoneNumberValue = contact.phoneNumbers.firstObject;
   NSString *label = phoneNumberValue.label;
   label = [CNLabeledValue localizedStringForLabel:label];
   NSLog(@"Phone Label: %@",label); //Logs value like _$!<Home>!$_