其实获取通讯录的代码都是死得, 千篇一律, 并没有什么花儿, 网上一搜一大把, 我写出来的意义其实仅仅是记录一下
- (void) getAllContactsInfo {
NSMutableArray *allContactsInfo = [[NSMutableArray alloc] initWithCapacity:1];
// get all contacts info and upload them:
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSInteger numberOfPeople = [allPeople count];
NSLog(@"%@",allPeople);
for (NSInteger i = 0; i < numberOfPeople; i++) {
NSMutableDictionary *contactInfo = [[NSMutableDictionary alloc] initWithCapacity:1];
ABRecordRef person = (__bridge ABRecordRef)allPeople[i];
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSLog(@"Name:%@ %@", firstName, lastName);
[contactInfo setObject:[NSString stringWithFormat:@"%@ %@", firstName, lastName] forKey:@"name"];
NSMutableArray *allPhoneNumbers = [[NSMutableArray alloc] initWithCapacity:1];
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
NSString *phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, i));
NSLog(@" phone:%@", phoneNumber);
[allPhoneNumbers addObject:phoneNumber];
}
[contactInfo setObject:allPhoneNumbers forKey:@"phone_numbers"];
NSMutableArray *allAddresses = [[NSMutableArray alloc] init];
ABMultiValueRef addresses = ABRecordCopyValue(person, kABPersonAddressProperty);
CFIndex numberOfAddresses = ABMultiValueGetCount(addresses);
for (CFIndex i = 0; i < numberOfAddresses; i ++) {
NSString *address = CFBridgingRelease(ABMultiValueCopyValueAtIndex(addresses, i));
NSLog(@" address:%@", address);
[allAddresses addObject:address];
}
[contactInfo setObject:allAddresses forKey:@"addresses"];
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:1];
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex numberOfEmails = ABMultiValueGetCount(emails);
for (CFIndex i = 0; i < numberOfEmails; i ++) {
NSString *email = CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, i));
NSLog(@" email:%@", email);
[allEmails addObject:email];
}
[contactInfo setObject:allEmails forKey:@"emails"];
CFRelease(phoneNumbers);
CFRelease(addresses);
CFRelease(emails);
NSLog(@"=============================================");
[allContactsInfo addObject:contactInfo];
}
NSLog(@"All contacts: %@", allContactsInfo);
}
以上便是简单地获取通讯录, 并且格式也都写好有了