adding contacts from iphone contacts to my table view - iphone

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..!!

Related

NSMutableArray Display Null Value in Table View

- (void)viewDidLoad {
self.detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
self.detailView.dataSource = self;
self.detailView.delegate = self;
self.detailView.multipleTouchEnabled=YES;
[self.view addSubview:self.detailView];
[super viewDidLoad];
self.title = NSLocalizedString(#"Routes", nil);
self.detailArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Chennai&destination=Madurai&sensor=false"];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
NSArray *legs = [dic objectForKey:#"legs"];
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detailArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
}
}
}
}
});
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
return cell;
}
i want to display the detailArray in the Table View.But it display null values in Table View.But in NSlog it display current values.The detailArray having set of direction values. is any possible to display in TableView.if i give constant value in displayArray its show correctly in TableView. please help me if Any one know.i am waiting for your valuable Answers,Thanks.
UPDATED
After add whole data (values) in after retain it and reload TableView like bellow...
[self.detailArray retain];
[self.detailView reloadData];
i am sure your problem solved... :)
Remove [self.detailView reloadData]; from cellForRowAtIndexPath method. and also remove tableView.delegate = self; in same method.
and remember [super viewDidLoad]; must write at top of viewDidLoad.
Edit
just change your four array as below.
NSArray *legs=(NSArray *)[dic objectForKey:#"legs"];
NSArray *arr = (NSArray *)[parsedJson objectForKey:#"routes"];
NSArray *legs = (NSArray *)[dic objectForKey:#"legs"];
NSArray *stepsArr = (NSArray *)[[legs objectAtIndex:i] objectForKey:#"steps"];
Why are you setting detailView delegate and datasource 2 times in viewDidLoad. Please format the code first then it will be easy for us to describe the problem.
self.detailView.dataSource=self;
self.detailView.delegate=self;
self.detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
self.detailView.dataSource = self;
self.detailView.delegate = self;

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!!!!

Custom addressbook ABPeoplePickerViewController help please?

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

self performSelector:#selector(loadData) withObject:nil - not working

I use:
self performSelector:#selector(loadData) withObject:nil...
it look like working with some command only in "loadData" but the rest are not.
Here is my viewdidload:
- (void)viewDidLoad
{
[super viewDidLoad];
[mActivity startAnimating];
[self performSelector:#selector(loadData) withObject:nil afterDelay:2];
//[mActivity stopAnimating];
}
and here is loadData:
-(void)loadData
{
[mActivity startAnimating];
NSLog(#"Start LoadData");
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *selectData=[NSString stringWithFormat:#"select * from k_proverb ORDER BY RANDOM()"];
qlite3_stmt *statement;
if(sqlite3_prepare_v2(delegate.db,[selectData UTF8String], -1,&statement,nil)==SQLITE_OK){
NSMutableArray *Alldes_str = [[NSMutableArray alloc] init];
NSMutableArray *Alldes_strAnswer = [[NSMutableArray alloc] init];
while(sqlite3_step(statement)==SQLITE_ROW)
{
NSString *des_strChk= [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,3)];
if ([des_strChk isEqualToString:#"1"]){
NSString *des_str= [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,4)];
[Alldes_str addObject:des_str];
}
}
Alldes_array = Alldes_str;
Alldes_arrayAnswer = Alldes_strAnswer;
}else{
NSLog(#"ERROR '%s'",sqlite3_errmsg(delegate.db));
}
listOfItems = [[NSMutableArray alloc] init];
NSDictionary *desc = [NSDictionary dictionaryWithObject:
Alldes_array forKey:#"description"];
[listOfItems addObject:desc];
//[mActivity stopAnimating];
NSLog(#"Finish loaData");}
it give me only printing 2 line, but did not load my Data to the table, but if I copy all the code from inside "loadData" and past in "viewDidLoad", it load the data to the table.
Any advice or help please.
A few things: If you see any NSLog output at all, then the performSelector is succeeding. You should change the title of your question.
If you are trying to load data into a table, the method should end with telling the UITableView to reloadData (or a more elaborate load using begin/end updates).
If the listOfItems is the data supporting the table, get this working first by hard-coding something like this:
-(void)loadData {
listOfItems = [NSArray arrayWithObjects:#"test1", #"test2", nil];
[self.tableView reloadData];
return;
// keep all of the code you wrote here. it won't run until you remove the return
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *string = [listOfItems objectAtIndex:indexPath.row];
cell.textLabel.text = string;
return cell;
// keep all of the code you probably wrote for this method here.
// as above, get this simple thing running first, then move forward
}
Good luck!

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>