1

我想从 iphone 模拟器获取所有联系方式,我已经阅读了与这个问题相关的不同问题,但我仍然无法完成这项工作。我是 iPhone 编程的新手,所以请从头开始帮助我。给我任何一步一步定义所有事情的教程链接。

4

2 回答 2

2

以下代码用于访问通讯录

- (void)viewDidLoad {
    [super viewDidLoad];
    contactList=[[NSMutableArray alloc] init];
    ABAddressBookRef m_addressbook = ABAddressBookCreate();

    if (!m_addressbook) {
        NSLog(@"opening address book");
    }

    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);
    CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);

    for (int i=0;i < nPeople;i++) { 
        NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];

        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);

        //For username and surname
        ABMultiValueRef phones =(NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty);
        CFStringRef firstName, lastName;
        firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        lastName  = ABRecordCopyValue(ref, kABPersonLastNameProperty);
        [dOfPerson setObject:[NSString stringWithFormat:@"%@ %@", firstName, lastName] forKey:@"name"];

        //For Email ids
        ABMutableMultiValueRef eMail  = ABRecordCopyValue(ref, kABPersonEmailProperty);
        if(ABMultiValueGetCount(eMail) > 0) {
            [dOfPerson setObject:(NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:@"email"];

        }

        //For Phone number
        NSString* mobileLabel;
        for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
            mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
            if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
            {
                [dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:@"Phone"];
            }
            else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
            {
                [dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:@"Phone"];
                break ;
            }

        [contactList addObject:dOfPerson];
        CFRelease(ref);
        CFRelease(firstName);
        CFRelease(lastName);
    }
    NSLog(@"array is %@",contactList);
    }
}

愿这对你有所帮助。

于 2013-01-07T12:50:50.553 回答
0

您可以ABAddressBookCopyArrayOfAllPeopleInSource使用 ABPersonRef

CFArrayRef ABAddressBookCopyArrayOfAllPeopleInSource (
   ABAddressBookRef addressBook,
   ABRecordRef source
);
于 2013-01-07T12:49:12.477 回答