Custom addressbook ABPeoplePickerViewController help please? - iphone

I need help with a custom AddressBook (ABPeoplePickerViewController) for iPhone?
I want to have an array with all my contacts, pulling just their name and numbers into the cells of the tableview to display.. Select a few contacts, open Messages and send them a Text/SMS with a custom message..
WhatsApp messenger is an awesome example, if you go to Settings, Tell a Friend, then Message..
I want that look!
It must be custom as I also want the Send and Cancel buttons below, and Name in cell.textLabel and their number in the cell.detailTextLabel in a Subtitle style tableview.
So how do I get their details from addressbook and into my arrays (contactsName, contactsNumber)? Thanks in advance! Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [contactsName objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [contactsNumber objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[self dismissViewControllerAnimated:YES completion:^{ NSLog(#"Message controller has been canceled"); }];
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
NSString *name = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *number = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSLog(#"Name: %# Number: %#", name, number);
return NO;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return NO;
}
- (void)openSMScontroller {
MFMessageComposeViewController *smsView = [[MFMessageComposeViewController alloc] init];
smsView.messageComposeDelegate = self;
smsView.recipients = [NSArray arrayWithArray:contactsNumber];
smsView.body = #"Check out this awesome app!";
[self presentModalViewController:smsView animated:YES];
}

you can get what you want from addressbook by below code my friend.!!!!!
happy coding!!!!!!
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);
NSArray *address = (NSArray *)ABMultiValueCopyArrayOfAllValues(addressProperty);
if([address count] > 0)
{
for (NSDictionary *addressDict in address)
{
countrytf.text = [addressDict objectForKey:#"Country"];
streetaddresstf.text = [addressDict objectForKey:#"Street"];
citynametf.text = [addressDict objectForKey:#"City"];
statenametf.text = [addressDict objectForKey:#"State"];
zipcodetf.text = [addressDict objectForKey:#"ZIP"];
}
CFRelease(addressProperty);
}
}

To get phone number...
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* phone = (NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, 0);
nslog(#"phone:%#",phone);
let me know it is working or not !!!!!!please if it is right then reward it and i know it is right..
Happy Coding

Related

customize the ABPersonPickerViewController

How can we customize the ABPeoplePickerNavigationViewController to display FullName in the first line and email,phone number in the next line. This should not happen on a contact select but should default when the ABPickerController view is loaded.
What I want is the regular functionalities of the ABPeoplePicker.. but the contacts display should have additional information explained above.
I think I would have to extend the ABPeoplePickerNavigationController? Any guidance on this would be greatly appreciated?
If you would want the ABPeoplePicker.... and the addressBook to work together dont quite have a solution.Tried the same thing but finally we spun out a new custom indexed table view. Was quite easy.
if you want an indexed tableView created please have a look at
indexed-ui-tableview
you could then change the following method for having information in multiple lines.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[[content objectAtIndex:indexPath.section] objectForKey:#"rowValues"]
objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[NSString stringWithFormat:#"%# %# %#", #"someone#gmail.com", #"|",#"123456777777777777777"] ;;
return cell;
}
The data generator can be modified to accomodate your model.
the email etc can be obtained from your model.In the snippet above it is hard coded.You could then easily wire in the search functionality.
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
// assigning control back to the main controller
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
NSString *firstname=(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
Usernametf.text=firstname;
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);
NSArray *address = (NSArray *)ABMultiValueCopyArrayOfAllValues(addressProperty);
NSString* phone;
phone = (NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, 0);
phoneNotf.text=phone;
//NSLog(#"%#",phone);
if([address count] > 0)
{
for (NSDictionary *addressDict in address)
{
NSString* countrytf = [addressDict objectForKey:#"Country"];
NSString* streetaddresstf= [addressDict objectForKey:#"Street"];
NSString* citynametf = [addressDict objectForKey:#"City"];
NSString* statenametf = [addressDict objectForKey:#"State"];
NSString* zipcodetf = [addressDict objectForKey:#"ZIP"];
}
CFRelease(addressProperty);
}
// NSMutableDictionary *dict=[[NSMutableDictionary alloc] initWithObjectsAndKeys:firstname,#"FirstName", nil];
//[selectedemailArray addObject:dict];
// NSLog(#"\n array is %#",selectedemailArray);
//[objDatabase insertArray:selectedemailArray forTable:#"EmailList"];
//[objDatabase insertDictionary:dict forTable:#"EmailList"];
// [dict release];
// dict =nil;
// remove the controller
[self dismissModalViewControllerAnimated:YES];
return NO;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
return NO;
}
here is whole code where you can get anything from contacts.
let me know it is working or not...
Happy Coding!!!!

How can I get all phone numbers from addressbook IOS 5 KABPersonPhoneProperty

I am using kABPersonPhoneProperty to get the iPhone "phone numbers" from the address book. However, once I run the program and only one phone number appears even the contact person has mobile, home and iphone numbers. Please help and I hope can get all phone numbers from every contact. Thanks.
The full method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// cell.textLabel.text = [people objectAtIndex:indexPath.row];
ABRecordRef record = (__bridge ABRecordRef) [people objectAtIndex:[indexPath row]];
NSString *firstName = (__bridge_transfer NSString*)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString*)ABRecordCopyValue(record, kABPersonLastNameProperty);
NSLog(#"FirstName %#, LastName %#", firstName, lastName);
cell.nameLabel.text = [NSString stringWithFormat:#"%# %#", firstName, lastName];
ABMultiValueRef mainPhone = ABRecordCopyValue(record, kABPersonPhoneProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(mainPhone); i ++) {
NSString *phoneMobileNumber = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(mainPhone, i);
cell.telNo.text = [NSString stringWithFormat:#"%# %#" , home, phoneMobileNumber];
NSLog(#"%#,%#", home, phoneMobileNumber);
}
return cell;
}
ok here is solution
` ABAddressBookRef addressBook=ABAddressBookCreate();
NSArray *allPeople=(NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *holdEachPersonMobileNumbers=[NSMutableArray new];
for (id person in allPeople) {
ABMultiValueRef phoneNumbers = ABRecordCopyValue(( ABRecordRef)(person), kABPersonPhoneProperty);
NSString* mobile=#"";
for (int i=0; i < ABMultiValueGetCount(phoneNumbers); i++) {
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, i);
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"#();$&-+"];
mobile = [[mobile componentsSeparatedByCharactersInSet: trim] componentsJoinedByString: #""];
mobile= [mobile stringByReplacingOccurrencesOfString:#"\"" withString:#""];
mobile=[mobile stringByReplacingOccurrencesOfString:#" " withString:#""];
[holdEachPersonMobileNumbers addObject:mobile];
}
}
`
Here holdEachPersonMobileNumbers hold all numbers associated to particular person which u select in address book
put above code in this method
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
Hope u conform this protocol ABPeoplePickerNavigationControllerDelegate
and import this
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

Automatically suggest name(s) from contact list with respect to letter entered in textfield

I have a textfield where the user enters the name.Now when a letter is typed in the textfield,let's say "T",then how can I get suggestions of names from contact list in iphone with respect to that letter entered.
Also I need to display the appropriate number corresponding to the name entered.
I have gone through apple documentation,
Can anyone please help me out with valuable suggestions or sample code snippet:
Thanks in advance :)
EDIT
I was able to view the contacts in log(console),as I wrote the code suggested by Mr.Anil Kothari in viewDidLoad method
As suggested by Mr.Anil Kothari,I have implemented the search bar code for textfield delegate methods as follows:
- (void)textFieldDidBeginEditing:(UITextField *)atextField
{
if(searching)
return;
searching = YES;
}
- (void) searchTableView
{
textField = [self.fields objectAtIndex:0];
NSString *searchText = textField.text;
for (UIView *subview in searchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]])
{
textField = (UITextField *)subview;
break;
}
}
textField.enablesReturnKeyAutomatically = NO;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
//searchArray contains matched names of friends with the searching string
for (NSString *sTemp in contactList)
{
txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
textField = [self.fields objectAtIndex:0];
txtToSearch = textField.text;
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
-(BOOL)textField:(UITextField *)atextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[copyListOfItems removeAllObjects];
if([string length] > 0)
{
searching = YES;
[self searchTableView];
}
else
{
searching = NO;
}
}
But still not working :(
Check the Code I have already done in some application this kind of stuff:-
- (void)viewDidLoad {
[super viewDidLoad];
self.tblSearchList.tableHeaderView = searchBar;
contactList=[[NSMutableArray alloc]init];
copyListOfItems=[[NSMutableArray alloc]init];
ABAddressBookRef addressBook = ABAddressBookCreate( );
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBook );
CFIndex nPeople = ABAddressBookGetPersonCount( addressBook );
for ( int i = 0; i < nPeople; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex( allPeople, i );
NSString *contactName =[[NSString alloc] initWithString:(NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty)];
NSLog(#"% # ",contactName);
[contactList addObject:contactName];
[contactName release];
}
}
searchBar Delegate's
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
if(searching)
return;
searching = YES;
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
[copyListOfItems removeAllObjects];
if([searchText length] > 0) {
searching = YES;
[self searchTableView];
}
else {
searching = NO;
}
[self.tblSearchList reloadData];
}
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
//searchArray contains matched names of friends with the searching string
for (NSString *sTemp in contactList)
{
NSString *txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
- (void) doneSearching_Clicked:(id)sender {
searchBar.text = #"";
[searchBar resignFirstResponder];
searching = NO;
[self.tblSearchList reloadData];
}
tableView Delegate's
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (searching)
return [copyListOfItems count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(searching)
return #"Search Results";
return #"";
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if(searching)
cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
return cell;
}
fell free to ask for any further queries..
You should use UISearchBar, implement the delegate method:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
Take the letter\s from searchText and fetch the contacts using ABAddressBookRef then update the SearchDisplayController accordingly..
hope this helps a little

iOS Address Book error on ABMultiValueRef

I'm facing a problem accessing the address book of my iPad 2. In particular I have problems retrieving the email of my contacts. What I want to do is to access the address book, retrieve my contacts and show them in a table view. Everything seems work fine since the name and the surname of the contacts are shown. The problem is with the email property since when I try to retrieve it I get an "EXC_BAD_ACCESS".
The code i wrote to show the tableview record is the following:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *tableIdentifier = #"tableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableIdentifier] autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
NSUInteger row = [indexPath row];
NSString *firstName = (NSString *)ABRecordCopyValue([contacts objectAtIndex:row], kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue([contacts objectAtIndex:row], kABPersonLastNameProperty);
NSString *name = [[NSString alloc] initWithFormat:#"%# %#", lastName,firstName];
[firstName release];
[lastName release];
cell.textLabel.text = name;
[name release];
NSArray *emails = [[self getEmailForPerson:row] retain];
/*......*/
return cell;
}
While the function to get the email of my contacts is the following:
- (NSArray *)getEmailForPerson:(NSInteger)index{
//Create the array where emails will be stored
NSMutableArray *m = [[[NSMutableArray alloc] init] autorelease];
//Get the email properties
ABMultiValueRef mails = ABRecordCopyValue([self.contacts objectAtIndex:index], kABPersonEmailProperty);
//Iterate in the multi-value properties
for (int i=0; i<ABMultiValueGetCount(mails); i++) {
//Get the email
NSString *mail = (NSString *) ABMultiValueCopyValueAtIndex(mails, i);
//Add the email to the array previously initializated
[m addObject:mail];
[mail release];
}
CFRelease(mails);
return m;
}
When I run the debugger after this statement
ABMultiValueRef mails = ABRecordCopyValue([self.contacts objectAtIndex:index], kABPersonEmailProperty);
mails seems not initialized since its adress is 0x0 but I cannot understand why.
I hope somebody can help me.
Thanks in advance
ABMultiValueRef mails = ABRecordCopyValue([self.contacts objectAtIndex:index], kABPersonEmailProperty);
It works fine in my app.
Check framework & self.contacts.
My app use two frameworks.
#import <AddressBook/AddressBook.h>
#import <AddressBook/ABAddressBook.h>

adding contacts from iphone contacts to my table view

i want add contacts to a table view and i am able to add all contacts to my table view by using the following code but i want to add selected contacts from phone contacts to my table view .
can any one please help me how to change the following code .....
-(void)loadTableSource{
contactsToBeAdded=[[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
//CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook,CFSTR("Rajesh"));
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for(int i=0;i<nPeople;i++){
ABRecordRef person=CFArrayGetValueAtIndex(people, i);
NSString *firstName=(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName=(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *organization=(NSString *)ABRecordCopyValue(person, kABPersonOrganizationProperty);
if(!firstName) firstName=#"";
if(!lastName) lastName=#"";
if(!organization) organization=#"";
NSDictionary *curContact=[NSDictionary dictionaryWithObjectsAndKeys:(NSString *)firstName,#"firstName",lastName,#"lastName",organization,#"organization",nil];
[contactsToBeAdded addObject:curContact];
}
CFRelease(people);
CFRelease(addressBook);
[self setTableSource:contactsToBeAdded];
[contactsToBeAdded release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdent=[NSString stringWithFormat:#"c%i",indexPath.row];
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdent];
if(cell==nil){
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdent];
NSDictionary *dict=[tableSource objectAtIndex:indexPath.row];
UILabel *lab=[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 310, 40)];
NSLog(#"lable:%#",tableSource);
[lab setNumberOfLines:2];
[lab setText:[[NSString stringWithFormat:#"%# %#\n%#",(NSString *)[dict objectForKey:#"firstName"],[dict objectForKey:#"last_name"],[dict objectForKey:#"organization"]] stringByReplacingOccurrencesOfString:#"(null)" withString:#""]];
[cell.contentView addSubview:lab];
[lab release];
}
return cell;
}
you didn't specify on what condition you are going to iterate contacts..
just check using if () before adding curContact dictionay to contactsToBeAdded array
if([firstName hasPrefix:#"A"])
{
NSDictionary *curContact=[NSDictionary dictionaryWithObjectsAndKeys:(NSString *)firstName,#"firstName",lastName,#"lastName",organization,#"organization",nil];
[contactsToBeAdded addObject:curContact];
}
i think this will help..!!