使用“联系人”框架获取本地化的电话标签

时间:2016-02-19 09:23:21

标签: ios cncontact cncontactstore contacts-framework

我正在尝试使用CNContact.My到目前为止获取本地化的手机标签值:

    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);
    }];

问题是手机标签返回的原始值如_$!<Home>!$__$!<Mobile>!$_。但我需要纯文本,如主页移动。有什么办法可以使用Contact框架获取本地化的值。我不想使用Addressbook,因为它在iOS 9中已被弃用。

3 个答案:

答案 0 :(得分:15)

使用CNLabeledValue类方法+ localizedStringForLabel:并传递标签

示例:

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

答案 1 :(得分:8)

这里是Swift 3:

let displayNumbers = contact.phoneNumbers.map() {
    let label = CNLabeledValue<NSString>.localizedString(forLabel: $0.label ?? "")
    return label + ": \u{200E}" + $0.value.stringValue
}

添加了unicode LeftToRight覆盖,以确保RTL语言不反转该数字。

答案 2 :(得分:1)

添加此行联系人访问

 if contact.isKeyAvailable(CNContactPhoneNumbersKey){

         for phoneNumber:CNLabeledValue in contact.phoneNumbers {
                        let number  = phoneNumber.value

                        let number2 = number.stringValue

                        let lable :String  =  CNLabeledValue<NSString>.localizedString(forLabel: phoneNumber.label! )

                        print("\(lable)  \(number.stringValue)")
                    }


                }