IOS::如何从ABAddressBook获取联系电话



电话号码变成这样。电话ABMultiValueRef 0x17674380,带1个值0:$$(0x176740e0)-7124779070(0x176742a0)

如何从上面的行中获得此数字"7124779070"。

我正在为ios 7使用此代码。它是正确的还是错误的,请告诉我。

 int i;
    ABAddressBookRef contactBook = ABAddressBookCreateWithOptions(NULL, NULL);
    NSMutableArray *allData = ( NSMutableArray *)(ABAddressBookCopyArrayOfAllPeople(contactBook));
    CFIndex contactNum = CFArrayGetCount((__bridge CFArrayRef)(allData));
    for (i = 0; i < contactNum; i++)
    {
        ABRecordRef ref = CFArrayGetValueAtIndex((__bridge CFMutableArrayRef)(allData), i);
        NSString*  firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        NSString* lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
        NSString*  phonesNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
        // Remove all formatting symbols that might be in both phone number being compared
        NSCharacterSet *toExclude = [NSCharacterSet characterSetWithCharactersInString:@"/.()- "];
        phonesNum = [[phonesNum componentsSeparatedByCharactersInSet:toExclude] componentsJoinedByString: @""];
    NSString *phoneNumber = [[phonesNum componentsSeparatedByCharactersInSet:toExclude] componentsJoinedByString: @""];

        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        if (firstName!=nil)
        {
            [dic setObject:(__bridge id)(firstName) forKey:@"firstName"];
        }
        if (lastName !=nil) {
            [dic setObject:(__bridge id)(lastName) forKey:@"lastName"];
        }
        if (phonesNum!=nil) {
            [dic setObject:(__bridge id)(phonesNum) forKey:@"phonesNum"];
        }
        [arr_Contacts addObject:dic];
        NSLog(@"First name %@", firstName);
        NSLog(@"Last Name %@", lastName);
        NSLog(@"Phone %@", phonesNum);
    }

首先,请求权限:

ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
if (status != kABAuthorizationStatusAuthorized && status != kABAuthorizationStatusNotDetermined) {
    // tell user to enable contacts in privacy settings
    NSLog(@"You previously denied access: You must enable access to contacts in settings");
    return;
}
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (!addressBook) {
    NSLog(@"ABAddressBookCreateWithOptions error: %@", CFBridgingRelease(error));
    return;
}
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
    if (error) {
        NSLog(@"ABAddressBookRequestAccessWithCompletion error: %@", CFBridgingRelease(error));
    }
    if (granted) {
        [self getContacts:addressBook];
    } else {
        // tell user to enable contacts in privacy settings
        NSLog(@"You just denied access: You must enable access to contacts in settings");
    }
    CFRelease(addressBook);
});

其次,要检索电话号码,请使用ABMultiValueCopyValueAtIndex:

- (void)getContacts:(ABAddressBookRef)addressBook
{
    NSArray *allData = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
    NSInteger contactCount = [allData count];
    for (int i = 0; i < contactCount; i++) {
        ABRecordRef person = CFArrayGetValueAtIndex((__bridge CFArrayRef)allData, i);
        NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        if (firstName) {
            dictionary[@"firstName"] = firstName;
        }
        if (lastName) {
            dictionary[@"lastName"]  = lastName;
        }
        ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        CFIndex phoneNumberCount = ABMultiValueGetCount(phones);
        if (phoneNumberCount > 0) {
            NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, 0));
            dictionary[@"phone"] = phone;
        }
        // or if you wanted to iterate through all of them, you could do something like:
        //
        // for (int j = 0; j < phoneNumberCount; j++) {
        //      NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, j));
        //
        //     // do something with `phone`
        // }
        if (phones) {
            CFRelease(phones);
        }
        [arr_Contacts addObject:dictionary];
    }
}

上面提到的几个附加问题:

  1. ABAddressBookCreateWithOptions不返回可变数组。它是一个不可变的数组。将所有这些可变引用替换为不可变引用。

  2. 您必须遵守创建规则,即您负责释放从名称为CreateCopy的Core Foundation方法返回的任何对象。如果对象支持免费桥接(例如联系人数组、名字字符串、姓氏字符串等),则可以使用CFBridgingRelease__bridge_transfer将所有权转移到ARC。如果对象不支持免费桥接(例如上面的phonesaddressBook对象),则必须为有问题的对象显式调用CFRelease

    请确保通过静态分析器运行代码(shift+命令+B,或者从Xcode的"产品"菜单中选择"分析"),它会为您确定这类问题。

  3. 如果一个函数,比如ABAddressBookCreateWithOptions提供了一个错误参数,你应该利用它。我在上面说明了CFErrorRef对象的正确使用。

您在控制台中从Phone%@NSLog收到了什么?如果电话ABMultiValueRef 0x17674380有1个值0:$!!$(0x176740e0)-7124779070(0x176742a0)仅在"-"之后的子字符串

NSString *myString = @"Phone ABMultiValueRef 0x17674380 with 1 value(s) 0: $!!$ (0x176740e0) - 7124779070 (0x176742a0)";
NSArray *myArray = [myString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-"]];    

这是我获取手机的方法

   - (void) getContacts
    {
    NSMutableDictionary *response = [[NSMutableDictionary alloc] init];
    ABAddressBookRef contactBook = ABAddressBookCreateWithOptions(NULL, NULL);
    arr_Contacts = [[NSMutableArray alloc] init];
    ABAddressBookRef allPeople = contactBook;
    CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(allPeople);
    CFIndex numberOfContacts  = ABAddressBookGetPersonCount(allPeople);
    NSLog(@"contact == %@",allContacts);

    NSLog(@"numberOfContacts------------------------------------%ld",numberOfContacts);
    for(int i = 0; i < numberOfContacts; i++){
        NSString* name = @"";
        NSString* phone = @"";
        NSString* email = @"";
        ABRecordRef aPerson = CFArrayGetValueAtIndex(allContacts, i);
        ABMultiValueRef fnameProperty = ABRecordCopyValue(aPerson, kABPersonFirstNameProperty);
        ABMultiValueRef lnameProperty = ABRecordCopyValue(aPerson, kABPersonLastNameProperty);
        ABMultiValueRef phoneProperty = ABRecordCopyValue(aPerson, kABPersonPhoneProperty);
        ABMultiValueRef emailProperty = ABRecordCopyValue(aPerson, kABPersonEmailProperty);
        NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
        NSArray *phoneArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);

        if (fnameProperty != nil) {
            name = [NSString stringWithFormat:@"%@", fnameProperty];
        }
        if (lnameProperty != nil) {
            name = [name stringByAppendingString:[NSString stringWithFormat:@" %@", lnameProperty]];
        }
        if ([phoneArray count] > 0) {
            if ([phoneArray count] > 1) {
                for (int i = 0; i < [phoneArray count]; i++) {
                    phone = [phone stringByAppendingString:[NSString stringWithFormat:@"%@, ", [phoneArray objectAtIndex:i]]];
                }
            }else {
                phone = [NSString stringWithFormat:@"%@", [phoneArray objectAtIndex:0]];
            }
        }
        if ([emailArray count] > 0) {
            if ([emailArray count] > 1) {
                for (int i = 0; i < [emailArray count]; i++) {
                    email = [email stringByAppendingString:[NSString stringWithFormat:@"%@n", [emailArray objectAtIndex:i]]];
                }
            }else {
                email = [NSString stringWithFormat:@"%@", [emailArray objectAtIndex:0]];
            }
        }
        NSLog(@"NAME : %@",name);
        NSLog(@"PHONE: %@",phone);
        NSLog(@"EMAIL: %@",email);
        NSLog(@"n");
        [response setObject:name forKey:@"name"];
        [response setObject:phone forKey:@"phone"];
        [response setObject:email forKey:@"email"];
      [arr_Contacts addObject:response];
    }
    }

干杯

最新更新