-(void)getContactsList{
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
if (accessGranted) {
ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil)
{
NSLog(@"Succesful.");
NSArray *allContacts = (__bridge_transfer NSArray
*)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger i = 0;
for (i = 0; i < [allContacts count]; i++)
{
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString
*)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString
*)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:@"%@ %@",
firstName, lastName];
ABMutableMultiValueRef multiEmail;
multiEmail = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);
NSString *emailAddress;
emailAddress = (__bridge NSString *) ABMultiValueCopyValueAtIndex(multiEmail, 0);
NSMutableDictionary *myAddressBook = [NSMutableDictionary dictionary];
[myAddressBook setValue:emailAddress forKey:@"email"];
[myAddressBook setValue:fullName forKey:@"fullName"];
[arrContacts addObject:myAddressBook];
//[arrContacts addObject:[myAddressBook valueForKey:@"email"]];
}
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"fullName" ascending:YES];
[arrContacts sortUsingDescriptors:[NSArray arrayWithObject:sort]];
}
CFRelease(addressBook);
}
}
No comments:
Post a Comment