xcode 如何从地址簿中获取电话号码作为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5618635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get phone number from address book as string?
提问by Upvote
I have a text field with a contact name and I want to get the phone number for that:
我有一个带有联系人姓名的文本字段,我想获取电话号码:
ABAddressBookRef adressBook = ABAddressBookCreate();
NSArray *people = (NSArray *)ABAddressBookCopyPeopleWithName(adressBook,
CFStringCreateCopy(kCFAllocatorDefault,
(CFStringRef)recipient));
if((people != nil) && ([people count] == 1)){
ABMultiValueRef person = (ABMultiValueRef)[people objectAtIndex:0];
NSString *phone = (NSString *)ABRecordCopyValue(person,
kABPersonPhoneProperty) ;
NSLog(@"%@", phone);
}
I want the phone number as string but this gives me a lot more:
我想要电话号码作为字符串,但这给了我更多:
ABMultiValueRef 0x339470 with 1 value(s)
0: _$!<Mobile>!$_ (0x338c50) - 0177 1647788 (0x339450)
How to I get just the number as string?
如何将数字作为字符串获取?
回答by unexpectedvalue
NSMutableArray *phoneNumbers = [[[NSMutableArray alloc] init] autorelease];
ABMultiValueRef multiPhones = ABRecordCopyValue(person,kABPersonPhoneProperty);
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);++i) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (NSString *) phoneNumberRef;
[phoneNumbers addObject:phoneNumber];
}
回答by Caleb
kABPersonPhoneProperty is a multi-value property, but you're treating it as a string. You should get the individual numbers and print them separately.
kABPersonPhoneProperty 是一个多值属性,但您将其视为字符串。您应该获取单独的数字并单独打印它们。
回答by Rafael Sanches
For those searching for phone extraction. You can extract the phone numbers from a text and then replace it with @"", for example:
对于那些搜索电话提取的人。您可以从文本中提取电话号码,然后将其替换为 @"",例如:
NSString *userBody = @"This is a text with 30612312232 my phone";
if (userBody != nil) {
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
NSArray *matches = [detector matchesInString:userBody options:0 range:NSMakeRange(0, [userBody length])];
if (matches != nil) {
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypePhoneNumber) {
DbgLog(@"Found phone number %@", [match phoneNumber]);
}
}
}
}
`
`
回答by malinois
CFStringRef phoneRef = ABRecordCopyValue(person, kABPersonPhoneProperty) ;
NSString *phoneNumber = (NSString *) phoneRef;