I have created a code for Addressbook and contacts where display the contacts.It was working properly but suddenly getting Run time error .As I'm new to ios .I'm not able to find the error can any one in the Stack Overflow tell the error.
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor yellowColor];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(gotohomepage:)]autorelease];
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
// Display only a person's phone, email, and birthdate
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];
picker.displayedProperties = displayedItems;
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (IBAction)gotohomepage:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
On iOS6, apple introduce new privacy control, user can control the accessment of contact and calender by each app. So, in the code side, you need to add some way to request the permission. In iOS5 or before, we can always call
ABAddressBookRef addressBook = ABAddressBookCreate();
to get the addressbook without any problem, but in iOS6, if you don't have permission, this call will just return empty pointer. That why we need to change the method to get ABAddressBookRef.
This type of error generally appears when permission is not granted to access address book.In that case please add this piece of code
__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);
dispatch_release(sema);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
if (accessGranted) {
// Do whatever you want here.
}
courtesy :- http://programmerjoe.blogspot.in/2012/10/ios6-permissions-contacts.html
If this doesn't solves your problem ping me back..
Error is that, because on IOS6 , Apple added some features that no one have permissions to get contents without owner's permission.
Related
Right now i am using the <AddressBookUI/AddressBookUI.h>
it is working fine, it is opening the address view controller, after tapping in a contact it goes to the detail view where I can click on any property to select and get the information.
below is the code i am using right now:
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
[self peoplePickerNavigationController:peoplePicker shouldContinueAfterSelectingPerson:person property:property identifier:identifier]; }
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
[picker dismissModalViewControllerAnimated:YES]; }
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier
{
ABMutableMultiValueRef multi = ABRecordCopyValue(person, property);
CFStringRef phone1 = ABMultiValueCopyValueAtIndex(multi, identifier);
NSLog(#"phone %#", (__bridge NSString *)phone1);
CFRelease(phone1);
ABMultiValueRef fnameProperty = ABRecordCopyValue(person, kABPersonFirstNameProperty);
ABMultiValueRef lnameProperty = ABRecordCopyValue(person, kABPersonLastNameProperty);
ABMultiValueRef phoneProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);
ABMultiValueRef emailProperty = ABRecordCopyValue(person, kABPersonEmailProperty);
NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSArray *phoneArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);
NSString *name,*phone,*email;
phone = [[NSString alloc]init];
email = [[NSString alloc]init];
name = [[NSString alloc]init];
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]];
}
}
//----setting txt field values
NSArray *f_name = [name componentsSeparatedByString:#" "];
if(f_name.count>1)
{
txtFirstname.text = [f_name objectAtIndex:0];
txtLastname.text = [f_name objectAtIndex:1];
}else{
txtFirstname.text = [f_name objectAtIndex:0];
}
NSArray *only_1_no = [phone componentsSeparatedByString:#","];
NSString *str = [only_1_no objectAtIndex:identifier];
NSCharacterSet *unwantedStr = [NSCharacterSet characterSetWithCharactersInString:#"+() -"];
str = [[str componentsSeparatedByCharactersInSet: unwantedStr] componentsJoinedByString: #""];
NSArray *ar = [email componentsSeparatedByString:#"\n"];
NSMutableString *abcd = [[NSMutableString alloc]init];
for (int i = 0; i<str.length; i++)
{
NSString *abc = [NSString stringWithFormat:#"%C",[phone characterAtIndex:i]];
if(i==0){
abcd =[NSMutableString stringWithFormat:#"%#",abc];
}else{
abcd = [NSMutableString stringWithFormat:#"%#%#",abcd,abc];
}
[self showmaskonnumber:abcd];
}
txtPhoneno.text = str;
txtEmail.text = [ar objectAtIndex:0];
ABPeoplePickerNavigationController *peoplePicker1 = (ABPeoplePickerNavigationController *)peoplePicker.navigationController;
[peoplePicker1 dismissModalViewControllerAnimated:YES];
[txtEmail becomeFirstResponder];
return YES;
}
my question is: Which changes should I make to this code so when I select a contact on the address list view, the selection returns the contact and all its information without showing its details?
I solved my issue by using this delegate method
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person;
{ [self selectedPerson:person]; }
In my app I have to access the address book, so in iOS>6.0 I have to ask permission to the user.
I do this:
ABAddressBookRef addressBook = ABAddressBookCreate();
if(floor(NSFoundationVersionNumber) >= NSFoundationVersionNumber_iOS_6_0)
{
//iOS is >= 6.0
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
if (granted)
{
[self showContacts:addressBook];
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
{
[self showContacts:addressBook];
}
else
{
//showAccessDeniedAlert();
}
}
else
{
//iOS is < 6.0
[self showContacts:addressBook];
}
In showContacts it's all alright, but: the first time I use the app on a device, it asks me if I want to let it access the AddressBook, i press "OK" and showContactsisn't called! So I have to close the app, restart it, and it works perfectly.
This is my showContacts method:
- (void) showContacts:(ABAddressBookRef)addressBook
{
CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfContacts = ABAddressBookGetPersonCount(addressBook);
for (int ii = 0; ii < numberOfContacts; ii++)
{
ABRecordRef contactRef = CFArrayGetValueAtIndex(allContacts, ii);
ABMultiValueRef *phones = ABRecordCopyValue(contactRef, kABPersonPhoneProperty);
for(CFIndex jj = 0; jj < ABMultiValueGetCount(phones); jj++)
{
CEPerson *person = [[CEPerson alloc] init];
NSString *name = (__bridge_transfer NSString *)ABRecordCopyValue(contactRef,kABPersonFirstNameProperty);
NSString *surname = (__bridge_transfer NSString *)ABRecordCopyValue(contactRef, kABPersonLastNameProperty);
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, jj);
NSString *phoneNumber = (__bridge NSString *)phoneNumberRef;
person.name = name;
person.surname = surname;
person.telephone = phoneNumber;
[arrContacts addObject:person];
}
}
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"surname" ascending:YES];
[arrContacts sortUsingDescriptors:[NSArray arrayWithObject:sort]];
[self selectAllContacts];
}
How can I make it work even right after the user presses "OK"?
Thank you all.
I figured it out. I simply added
[tableView reloadData];
at the end of my showContacts method.
I am having the trouble to fetch iPhone contacts.
I have tried to fetch the contact by the following code.
It is working fine in simulator and also worked fine when the contacts are less in the contact list.
In my phone I am having 1000 Contacts. So it crashes on this device. Please guide me if you know the reason.
Here is my code.
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];
for (int i = 0; i < nPeople; i++)
{
NSMutableDictionary *dicContacts = [[NSMutableDictionary alloc]init];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
[phoneNumbers addObject:phoneNumber];
//NSLog(#"All numbers %#", phoneNumbers);
}
if ([phoneNumbers count] > 0) {
[dicContacts setValue:[phoneNumbers objectAtIndex:0] forKeyPath:#"Contact"];
}
[items addObject:dicContacts];
}
Thanks In Advance
-(void)tkPeoplePickerController:(TKPeoplePickerController*)picker didFinishPickingDataWithInfo:(NSArray*)contacts
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL,error);
[contacts enumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop)
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
TKContact *contact = (TKContact*)obj;
NSNumber *personID = [NSNumber numberWithInt:contact.recordID];
ABRecordID abRecordID = (ABRecordID)[personID intValue];
ABRecordRef abPerson = ABAddressBookGetPersonWithRecordID(addressBook, abRecordID);
// Check person image
UIImage *personImage = nil;
if (abPerson != nil && ABPersonHasImageData(abPerson))
{
if ( &ABPersonCopyImageDataWithFormat != nil )
{
// iOS >= 4.1
CFDataRef contactThumbnailData = ABPersonCopyImageDataWithFormat(abPerson, kABPersonImageFormatThumbnail);
personImage = [UIImage imageWithData:(__bridge NSData*)contactThumbnailData];
CFRelease(contactThumbnailData);
ABMultiValueRef emailValues = ABRecordCopyValue(abPerson, kABPersonEmailProperty);
// This is how you extract the first item from the multivalues:
CFStringRef cfEmailAddress = ABMultiValueCopyValueAtIndex(emailValues, 0);
// This is how you convert it to an NSString.
[RSVP_ImageArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
contact.name,#"name",
contact.email,#"email",
[NSString stringWithFormat:#"%d",abRecordID],#"recodeID",
savedImagePath,#"Image",
nil]];
CFDataRef contactImageData = ABPersonCopyImageDataWithFormat(abPerson, kABPersonImageFormatOriginalSize);
CFRelease(contactImageData);
}
else
{
// iOS < 4.1
CFDataRef contactImageData = ABPersonCopyImageData(abPerson);
personImage = [[UIImage imageWithData:(__bridge NSData*)contactImageData] thumbnailImage:CGSizeMake(thumbnailSize, thumbnailSize)];
ABMultiValueRef emailValues = ABRecordCopyValue(abPerson, kABPersonEmailProperty);
// This is how you extract the first item from the multivalues:
CFStringRef cfEmailAddress = ABMultiValueCopyValueAtIndex(emailValues, 0);
// This is how you convert it to an NSString.
[RSVP_ImageArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
contact.name,#"name",
contact.email,#"email",
[NSString stringWithFormat:#"%d",abRecordID],#"recodeID",
savedImagePath,#"Image",
nil]];
CFRelease(contactImageData);
}
}
else
{
ABMultiValueRef emailValues = ABRecordCopyValue(abPerson, kABPersonEmailProperty);
// This is how you extract the first item from the multivalues:
CFStringRef cfEmailAddress = ABMultiValueCopyValueAtIndex(emailValues, 0);
// This is how you convert it to an NSString.
[mutablearray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
contact.name,#"name",
contact.email,#"email",
[NSString stringWithFormat:#"%d",abRecordID],#"recodeID",
savedImagePath,#"Image",
nil]];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
});
[pool drain];
}];
dispatch_async(dispatch_get_main_queue(), ^{
CFRelease(addressBook);
});
});
}
Use this code with it will surely help you.. for reference u can use this link https://github.com/qnibus/TKContactsMultiPicker ... :)
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
[phoneNumbers addObject:[NSString stringWithFormat:#"%#",phoneNumber]];
//NSLog(#"All numbers %#", phoneNumbers);
}
[phoneNumbers retain];
I am doing an iPhone app in Xcode that needs phone book accessing. I need all phone numbers from address book and that should be stored in an NSArray.
//Also you need to include AddressBook.framework
#import <AddressBook/AddressBook.h>
#import <AddressBook/ABAddressBook.h>
#import <AddressBook/ABPerson.h>
[contactList removeAllObjects];
// open the default address book.
ABAddressBookRef m_addressbook = ABAddressBookCreate();
if (!m_addressbook) {
NSLog(#"opening address book");
}
// can be cast to NSArray, toll-free
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);
CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);
// CFStrings can be cast to NSString!
for (int i=0;i < nPeople;i++) {
MContact *contact = [[MContact alloc] init];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
contact.name = [NSString stringWithFormat:#"%# %#", firstName, lastName];
ABMutableMultiValueRef eMail = ABRecordCopyValue(ref, kABPersonEmailProperty);
if(ABMultiValueGetCount(eMail) > 0) {
contact.email = (NSString *)ABMultiValueCopyValueAtIndex(eMail, 0);
[contactList addObject:contact];
}
CFRelease(ref);
CFRelease(firstName);
CFRelease(lastName);
}
Try this,
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
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];
}
This code for Xcode 4.5.1>=0, if if you have below version then no need write if condition. just assign ABAddressBookCreate() to addressbook.
__block BOOL accessGranted = NO;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"6.0")) {
NSLog(#"Device version is greater than 6.0");
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
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{
addressBook = ABAddressBookCreate();
accessGranted = YES;
}
if (accessGranted) {
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
ABRecordRef person = CFArrayGetValueAtIndex(people, i);
NSString *name = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
ABMultiValueRef multiPhones = ABRecordCopyValue(person,kABPersonPhoneProperty);
NSMutableArray *individualPhoneNumbers = [[NSMutableArray alloc] init];
if (ABMultiValueGetCount(multiPhones) >0) {
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);++i) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
[individualPhoneNumbers addObject:phoneNumber];
}
[phoneNumbers addObject:individualPhoneNumbers];
}
}
I've been looking the web for this solution. Its exactly like the google maps application on the iphone, where as you search, it looks through the address book to find suggestions for what your looking for.
What i managed to do so far is set up a search bar and a mapview, so when i search for the exact address i get it displayed on the map.
I want to make it easier for the users, who might have addresses stored in their address book to use it to search on the map view.
I know that you need to use search display controller and address book, but i can't find any examples of search display controller on other than a default table view.
this is what i have so far
EDIT.
I guess no one knows. But it took me a couple of days to figure it out.
Heres the solution for everyone wanting to learn how to do this.
The key thing to know here is how to get the address book data into an array that you can just use with the search display controller to filter it out.
So here is the method i came up with to get the address book data:
- (void) getContactData
{
NSMutableDictionary *myAddressBook = [[NSMutableDictionary alloc] init];
self.names = [NSMutableArray array];
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != nil){
NSLog(#"Successfully accessed the address book.");
NSArray *allPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSString *address;
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;
peopleCounter < [allPeople count]; peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef)
[allPeople objectAtIndex:peopleCounter];
NSString *firstName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonLastNameProperty);
NSString *company = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonOrganizationProperty);
ABMutableMultiValueRef multiValue = ABRecordCopyValue(thisPerson, kABPersonAddressProperty);
for(CFIndex i=0;i<ABMultiValueGetCount(multiValue);i++)
{
NSString* HomeLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
CFStringRef street = CFDictionaryGetValue(dict, kABPersonAddressStreetKey);
CFStringRef city = CFDictionaryGetValue(dict, kABPersonAddressCityKey);
CFStringRef state = CFDictionaryGetValue(dict, kABPersonAddressStateKey);
CFStringRef zip = CFDictionaryGetValue(dict, kABPersonAddressZIPKey);
CFRelease(dict);
if (zip == nil) {
address = [NSString stringWithFormat:#"%#, %#, %# ", street, city, state];
}else {
address = [NSString stringWithFormat:#"%#, %#, %# , %#", street, city, state, zip];
}
}
if ([address length] != 0) {
// [self.addresses insertObject:address atIndex:i];
[myAddressBook setObject:address forKey:#"Address"];
if ([firstName length] != 0 && [lastName length] != 0) {
NSString *name= [NSString stringWithFormat: #"%# %#", firstName, lastName];
[myAddressBook setObject:name forKey:#"Name"];
// [names insertObject:name atIndex:i];
}
else if ([firstName length] != 0 && [lastName length] == 0) {
NSString *name= [NSString stringWithFormat: #"%#", firstName];
// [names insertObject:name atIndex:i];
[myAddressBook setObject:name forKey:#"Name"];
}
else if ([firstName length] == 0 && [lastName length] == 0) {
if ([company length] != 0) {
//[names insertObject:company atIndex:i];
[myAddressBook setObject:company forKey:#"Name"];
}
}
NSString *name = [myAddressBook objectForKey:#"Name"];
NSString *address = [myAddressBook objectForKey:#"Address"];
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys:name,#"Name",address,#"Address",nil];
[self.names addObject:personDict];
}
}
}
CFRelease(addressBook);
}
}
// Setup SearchBar
UISearchBar *search = [[UISearchBar alloc] initWithFrame:CGRectMake(20, 0, 278, 44)];
search.delegate = self;
self.searchBar = search;
// Setup Map View
MKMapView *mapView = [[MKMapView alloc] initWithFrame:CGRectMake(20, 44, 278, 150)];
mapView.mapType = MKMapTypeStandard;
mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.myMapview = mapView;
[self.view addSubview:self.myMapview];
[self.view addSubview:self.searchBar];
- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar {
// When the search button is tapped, add the search term to recents and conduct the search.
NSString *searchString = [searchBar text];
self.eventLocationCoordinate = [self getLocationFromAddressString:searchString];
[self zoomMapAndCenterAtLatitude:self.eventLocationCoordinate.latitude andLongitude:self.eventLocationCoordinate.longitude];
[self setMapAnnotationAtCoordinate:self.eventLocationCoordinate withTitle:#"Your Here" andSubtitle:searchString];
}
Have fun coding!