I am trying to retrieve contacts from address book on iOS.
In my NSLOG all seems ok, but when I put all contacts to tableview (Labels etc), it's showing white cell and accessory only but 3 times ( I have only 3 contacts, and count working well in this case)
#interface ViewController ()
#end
#implementation ViewController
#synthesize searchBar,contactsTableView, retrievedContacts;
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"All Contacts";
self.tableData = [[NSMutableArray alloc] init];
retrievedContacts = [[NSMutableArray alloc] init];
self.contactsTableView.dataSource = self;
self.contactsTableView.delegate = self;
[self getPersons];
[self.contactsTableView reloadData];
}
-(void)getPersons {
// [retrievedContacts removeAllObjects];
int i;
ABAddressBookRef contactBook = ABAddressBookCreate();
NSMutableArray *allData = (__bridge_transfer NSMutableArray *)(ABAddressBookCopyArrayOfAllPeople(contactBook));
CFIndex contactNum = CFArrayGetCount((__bridge CFArrayRef)(allData));
for (i = 0; i < contactNum; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex((__bridge CFMutableArrayRef)(allData), i);
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
phonesNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
[retrievedContacts addObject:(__bridge id)(firstName)];
[retrievedContacts addObject:(__bridge id)(lastName)];
[retrievedContacts addObject:(__bridge id)(phonesNum)];
NSLog(#"First name %#", firstName);
NSLog(#"Last Name %#", lastName);
NSLog(#"Phone %#", phonesNum);
}
NSLog(#"Count Contacts %li", contactNum);
//self.tableData = retrievedContacts;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [retrievedContacts count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
abCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
}
cell.firstNameLabel.text = [retrievedContacts objectAtIndex:indexPath.row];
cell.lastNameLabel.text = [retrievedContacts objectAtIndex:indexPath.row];
return cell;
}
And here NSLOG Output:
2013-05-28 15:50:39.260 GTCallBack[39242:c07] First name: Anton
2013-05-28 15:50:39.261 GTCallBack[39242:c07] Last Name: SAnton
2013-05-28 15:50:39.262 GTCallBack[39242:c07] Phone numbers: ABMultiValueRef 0x797e6e0 with 2 value(s)
0: _$!<Mobile>!$_ (0x797ee30) - +972 (58) 123 4567 (0x797ee50)
1: iPhone (0x7976cc0) - +972 (58) 123 4567 (0x797ee10)
2013-05-28 15:50:39.262 GTCallBack[39242:c07] Contact Image: Anton
2013-05-28 15:50:39.263 GTCallBack[39242:c07] First name: Anton
2013-05-28 15:50:39.263 GTCallBack[39242:c07] Last Name: Anton
2013-05-28 15:50:39.264 GTCallBack[39242:c07] Phone numbers: ABMultiValueRef 0x6d8c560 with 1 value(s)
0: _$!<Mobile>!$_ (0x6d8c940) - (058) 123 4567 (0x6d8c960)
2013-05-28 15:50:39.268 GTCallBack[39242:c07] Contact Image: Anton
2013-05-28 15:50:39.269 GTCallBack[39242:c07] First name: Shalom
2013-05-28 15:50:39.270 GTCallBack[39242:c07] Last Name: Shalom
2013-05-28 15:50:39.270 GTCallBack[39242:c07] Phone numbers: ABMultiValueRef 0x7c689d0 with 1 value(s)
0: _$!<Mobile>!$_ (0x7c604c0) - (058) 123 4567 (0x7c6bff0)
2013-05-28 15:50:39.271 GTCallBack[39242:c07] Contact Image: Shalom
2013-05-28 15:50:39.301 GTCallBack[39242:c07] Count Contacts 3
Maybe there is another way to fill table with contacts data?
Thanks
First you need to get alloc init for array, custom cell labels also.
You not add data correctly in array.
for (i = 0; i < contactNum; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex((__bridge CFMutableArrayRef)(allData), i);
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
phonesNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:(__bridge id)(firstName) forKey:#"firstName"];
[dic setObject:(__bridge id)(lastName) forKey:#"lastName"];
[dic setObject:(__bridge id)(phonesNum) forKey:#"phonesNum"];
[retrievedContacts addObject:dic];
NSLog(#"First name %#", [dic objectForKey:#"firstName"]);
NSLog(#"Last Name %#", [dic objectForKey:#"lastName"]);
NSLog(#"Phone %#",[dic objectForKey:#"phonesNum"]);
}
Check if NSLog is printing working.
In cellForRow method access array in this way.
NSMutableDictionary *dic = [retrievedContacts objectAtIndex:indexPath.row];
cell.firstNameLabel.text = [dic objectForKey:#"firstName"];
cell.lastNameLabel.text = [dic objectForKey:#"lastName"];
I have finished my issue yesterday. Now all working.
Here is the code.
#import "ViewController.h"
#import "ContactDetailsViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize searchBar, contactsTableView;
- (void)viewDidLoad {
[super viewDidLoad];
contacts = [[Contacts alloc] init];
[contacts getContacts];
self.title = #"All Contacts";
self.contactsTableView.dataSource = self;
self.contactsTableView.delegate = self;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [contacts.firstNames count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
abCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
}
cell.firstNameLabel.text = [contacts.firstNames objectAtIndex:indexPath.row];
cell.lastNameLabel.text = [contacts.lastNames objectAtIndex:indexPath.row];
/*for (NSString *value in [retrievedContacts objectAtIndex:indexPath.row]) {
NSMutableArray *tmp = [[NSMutableArray alloc] init];
[tmp addObject:[[retrievedContacts objectAtIndex:indexPath.row] valueForKey:value]];
NSLog(#"Contact: %#", tmp);
}*/
/*NSLog(#"Name: %#", [[retrievedContacts objectAtIndex:indexPath.row] valueForKey:#"First Name"]);
NSLog(#"Familie: %#", [[retrievedContacts objectAtIndex:indexPath.row] valueForKey:#"Last Name"]);
NSLog(#"PHONE TYPE: %# • PHONE NUMBER: %#", [[[retrievedContacts objectAtIndex:indexPath.row] objectForKey:#"Phones"] valueForKey: #"Phone Label"], [[[retrievedContacts objectAtIndex:indexPath.row] objectForKey:#"Phones"] valueForKey: #"Phone Number"]);*/
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.contactsTableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"NextView"]) {
ContactDetailsViewController *nextController = [segue destinationViewController];
NSIndexPath *indexPath = [[[self contactsTableView] indexPathsForSelectedRows] objectAtIndex:0];
[nextController setPhoneTypes:[contacts.phoneTypes objectAtIndex:[indexPath row]]];
[nextController setPhoneNumbers:[contacts.phoneNumbers objectAtIndex:[indexPath row]]];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import "Contacts.h"
#implementation Contacts
#synthesize firstNames, lastNames, phoneTypes, phoneNumbers, photos, retrievedContacts;
-(void)getContacts {
ABAddressBookRef addressBook = ABAddressBookCreate();
__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) {
int i;
firstNames = [[NSMutableArray alloc] init];
lastNames = [[NSMutableArray alloc] init];
phoneTypes = [[NSMutableArray alloc] init];
phoneNumbers = [[NSMutableArray alloc] init];
photos = [[NSMutableArray alloc] init];
ABAddressBookRef contactBook = ABAddressBookCreate();
NSMutableArray *allData = (__bridge_transfer NSMutableArray *)(ABAddressBookCopyArrayOfAllPeople(contactBook));
contactNum = CFArrayGetCount((__bridge CFArrayRef)(allData));
retrievedContacts = [[NSMutableArray alloc] init];
for (i = 0; i < contactNum; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex((__bridge CFMutableArrayRef)(allData), i);
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
phonesNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
ContactImg = ABRecordCopyValue(ref, kABPersonImageFormatThumbnail);
ABMutableMultiValueRef phoneNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNum );
if (!firstName) {
[firstNames addObject:#"NO NAME"];
//NSLog(#"FN %# • LN %# • CI %#", firstName, lastName, ContactImg);
} else if (!lastName) {
[lastNames addObject:#"NO LAST NAME"];
} else if (!ContactImg) {
[photos addObject:#"NOIMG.png"];
} else {
/*NSMutableArray *person = [[NSMutableArray alloc] init];
[person addObject:(__bridge id)(firstName)];
[person addObject:(__bridge id)(lastName)];
//[person addObject:(__bridge id)(phonesNum)];
[person addObject:(__bridge id)(ContactImg)];
[retrievedContacts addObject:person];*/
[firstNames addObject:(__bridge id)(firstName)];
[lastNames addObject:(__bridge id)(lastName)];
[photos addObject:(__bridge id)(ContactImg)];
NSMutableArray *tmpType = [[NSMutableArray alloc] init];
NSMutableArray *tmpNumbr = [[NSMutableArray alloc] init];
for (int k = 0; k < phoneNumberCount; k++ )
{
CFStringRef phoneNumberLabel = ABMultiValueCopyLabelAtIndex( phoneNum, k );
CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex( phoneNum, k );
CFStringRef phoneNumberLocalizedLabel = ABAddressBookCopyLocalizedLabel( phoneNumberLabel ); // converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"
NSLog(#"-----PHONE ENTRY -> %# : %#\nPERSON NUM. %i • PHONE NUM. %i", phoneNumberLocalizedLabel, phoneNumberValue, i, k );
[tmpType addObject:(__bridge id)(phoneNumberLocalizedLabel)];
[tmpNumbr addObject:(__bridge id)(phoneNumberValue)];
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
}
[phoneTypes addObject:tmpType];
[phoneNumbers addObject:tmpNumbr];
#ifdef DEBUG
//NSLog(#"First name: %#", firstName);
//NSLog(#"Last Name: %#", lastName);
//NSLog(#"Phone numbers: %#", phonesNum);
//NSLog(#"Contact Image: %#", ContactImg);
//NSLog(#"Some Text %#", retrievedContacts); //Here everething is OK :)
#endif
}
}
}
}
#end
Hope it will save to someone a time.
Thanks to all
Try type casting like this:
cell.firstNameLabel.text = (NSString*)[retrievedContacts objectAtIndex:indexPath.row];
cell.lastNameLabel.text = (NSString*)[retrievedContacts objectAtIndex:indexPath.row];
Or you can try this before adding to array:
NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty);
I have used similar code and it worked for me.
Hope this helps.
Related
I have written this code
contactlistvc.h
#import <UIKit/UIKit.h>
#interface ContactListVc : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
UITableView *contactTable;
NSMutableArray *tableData;
}
#property (strong, nonatomic) IBOutlet UITableView *contactTable;
#property (nonatomic, strong) NSMutableArray *tableData;
contactlistvc.m
#import "ContactListVc.h"
#import <AddressBook/AddressBook.h>
#import "Person.h"
#interface ContactListVc ()
#end
#implementation ContactListVc
#synthesize tableData,contactTable;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationController.navigationBar.backgroundColor = [UIColor blueColor];
tableData = [[NSMutableArray alloc]init];
contactTable = [[UITableView alloc]init];
contactTable.dataSource = self;
contactTable.delegate = self;
[self getPersonOutOfAddressBook];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
Person *person = [self.tableData objectAtIndex:indexPath.row];
cell.textLabel.text = person.fullName;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getPersonOutOfAddressBook
{
//1
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil) {
NSLog(#"Succesful.");
NSLog(#"tabledata %#",tableData);
//2
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
//3
NSUInteger i = 0; for (i = 0; i < [allContacts count]; i++)
{
Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
//4
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,
kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
person.firstName = firstName; person.lastName = lastName;
person.fullName = fullName;
//email
//5
ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);
//6
NSUInteger j = 0;
for (j = 0; j < ABMultiValueGetCount(emails); j++) {
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
if (j == 0) {
person.homeEmail = email;
NSLog(#"person.homeEmail = %# ", person.homeEmail);
}
else if (j==1) person.workEmail = email;
}
//7
[self.tableData addObject:person];
}
//8
CFRelease(addressBook);
} else {
//9
NSLog(#"Error reading Address Book");
}
}
But i am not getting the contact list. only successfull is coming on console window. I am having 3 tab bar on one tab of contact i want to show the contact list of phone in tableview. Plz help me , thanks.
You need to first get permission to access the native DB...
- (void)requestPermissionForContactsAccessAndFetch
{
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
if (status != kABAuthorizationStatusAuthorized && status != kABAuthorizationStatusNotDetermined) {
// tell user to enable contacts in privacy settings
NSLog(#"You previously denied access: You must enable access to contacts in settings");
return;
}
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (!addressBook) {
NSLog(#"ABAddressBookCreateWithOptions error: %#", CFBridgingRelease(error));
return;
}
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (error) {
NSLog(#"ABAddressBookRequestAccessWithCompletion error: %#", CFBridgingRelease(error));
}
if (granted) {
[self getContactsFromAddressBook:addressBook];
} else {
// tell user to enable contacts in privacy settings
NSLog(#"You just denied access: You must enable access to contacts in settings");
}
CFRelease(addressBook);
});
}
Then you can get all contacts in an array...
- (NSMutableArray*)getContactsFromAddressBook:(ABAddressBookRef)addressBook
{
NSArray *allData = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSInteger contactCount = [allData count];
for (int i = 0; i < contactCount; i++) {
ABRecordRef person = CFArrayGetValueAtIndex((__bridge CFArrayRef)allData, i);
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
if (firstName) {
dictionary[#"firstName"] = firstName;
}
if (lastName) {
dictionary[#"lastName"] = lastName;
}
ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex phoneNumberCount = ABMultiValueGetCount(phones);
if (phoneNumberCount > 0) {
NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, 0));
dictionary[#"phone"] = phone;
}
// or if you wanted to iterate through all of them, you could do something like this...
// for (int j = 0; j < phoneNumberCount; j++) {
// NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, j));
// }
if (phones) {
CFRelease(phones);
}
[arrOfContacts addObject:dictionary];
}
}
Below is what I am using to retrieve the contacts list from the device. I want it to be displayed alphabetically but using other examples seen on stack overflow I have been unable to get it to work.
The code below is from a tutorial, what do I need to do to it to sort according to alphabetical order?
- (void)getPersonOutOfAddressBook
{
//1
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil) {
NSLog(#"Succesful.");
//2
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
//3
NSUInteger i = 0; for (i = 0; i < [allContacts count]; i++)
{
Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
//4
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,
kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
person.firstName = firstName; person.lastName = lastName;
person.fullName = fullName;
//email
//5
ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);
//6
NSUInteger j = 0;
for (j = 0; j < ABMultiValueGetCount(emails); j++) {
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
if (j == 0) {
person.homeEmail = email;
NSLog(#"person.homeEmail = %# ", person.homeEmail);
}
else if (j==1) person.workEmail = email;
}
//7
[self.tableData addObject:person];
}
//8
CFRelease(addressBook);
} else {
//9
NSLog(#"Error reading Address Book");
}
}
This is my UITableView code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
Person *person = [self.tableData objectAtIndex:indexPath.row];
cell.textLabel.text = person.fullName;
return cell;
}
I have tried below
[self.tableData sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
I have also tried NSSortDescriptor but I don't have a Key to sort by.
You'll need to sort the array of Person objects. Once you have finished adding them all to the array you can sort on the fullName using the following code:
[self.tableData sortUsingComparator:^NSComparisonResult(Person *p1, Person *p2) {
return [p1.fullName compare:p2.fullName];
}];
Alternative
You may want to implement a compare: method on the Person object and perform the comparison there, this will keep sorting logic nicely encapsulated and ensure that anything else that uses Person objects can easily perform sorts without duplicating the code shown above.
#implementation Person
// Mostly likely this implementation will contain more code, not shown for brevity
- (NSComparisonResult)compareByFullName:(Person *)otherPerson {
return [self.fullName compare:otherPerson.fullName];
}
#end
Then you can sort the array with:
[self.tableData sortUsingSelector:#selector(compareByFullName:)];
You need to implement and provide a method to sort a Person record as a selector for the sortUsingSelector method invocation.
I managed to solve it like this.
//keys with fetching properties NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactEmailAddressesKey]; CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
//Order contacts by Surname. request.sortOrder = CNContactSortOrderFamilyName;
--OR YOU CAN--
//Order contacts by Name. request.sortOrder = CNContactSortOrderGivenName;
I want to create program that will import contacts from adressbook and show them in tableview. I already did code to download contacts from adressbook but when I'm adding them into Array and then trying to show in TableView they don't appear when I'm starting app. Here's code:
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[self getPersonOutOfAddressBook];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
Person *person = [self.tableData objectAtIndex:indexPath.row];
cell.textLabel.text = person.fullName;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)getPersonOutOfAddressBook
{
//1
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // We are on iOS 6
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(semaphore);
});
}
if (addressBook != nil) {
NSLog(#"Succesful.");
//2
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
//3
NSUInteger i = 0; for (i = 0; i < [allContacts count]; i++)
{
Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
//4
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,
kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
person.firstName = firstName; person.lastName = lastName;
person.fullName = fullName;
[self.tableData addObject:person];
}
//8
CFRelease(addressBook);
} else {
//9
NSLog(#"Error reading Address Book");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
When I'm using debugger it shows that variables firstname, lastname and then fullname have access to adressbook because I can see name or last name of person. But I think there is problem with adding to array because I can't see anything in this array. Could someone help me? I'm beginner with Objective - C so please forbearance :)
To use an array you need to both declare it and create it. You do this by allocating and initializing the array.
self.tableData = [[NSMutableArray alloc] init];
I am using UISegmentedControl and using UITableView but my query is segment button 1 click and display data for yes and 2 button click and display data from no and adding A to Z section UITableView first button click properly data display and properly tableview section atoz display but 2 button click and app crash `
#import "ZnameViewController.h"
#import "ZpaleoViewController.h"
#import "SWRevealViewController.h"
#interface ZnameViewController ()
#end
#implementation ZnameViewController
#synthesize strname1,sagmentController,objtbl,name;
- (void)viewDidLoad {
[super viewDidLoad];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.slide setTarget: self.revealViewController];
[self.slide setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
databse = [FMDatabase databaseWithPath:appdelegate.appDBPath];
[arrCatname removeAllObjects];
[arrPaleo removeAllObjects];
arrCatname = [[NSMutableArray alloc]init];
arrPaleo = [[NSMutableArray alloc]init];
arrStatus = [[NSMutableArray alloc]init];
arrCat2 = [[NSMutableArray alloc]init];
arrSta2 = [[NSMutableArray alloc]init];
[self segmentSwitch:self];
// Do any additional setup after loading the view.
}
- (IBAction)segmentSwitch:(id)sender {
[databse open];
NSString *selectQuery = [NSString stringWithFormat:#"select * from Food ORDER BY name ASC"];
NSLog(#"%#",selectQuery);
FMResultSet *resultQuary = [databse executeQuery:selectQuery];
while ([resultQuary next]) {
// NSString *z_paleo = [resultQuary stringForColumn:#"status"];
z_paleo = [NSString stringWithFormat:#"%d",[resultQuary intForColumn:#"status"]];
if ([z_paleo isEqualToString:#"1"]) {
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrPaleo addObject:#""];
}
else{
[arrPaleo addObject:z_name];
}
[arrSta2 addObject:z_paleo];
}
else{
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrCatname addObject:#""];
}
else
{
[arrCatname addObject:z_name];
}
[arrCat2 addObject:z_paleo];
}
}
[databse close];
if(sagmentController.selectedSegmentIndex == 0)
{
if ([z_paleo isEqualToString:#"1"]) {
[self getName:arrPaleo];
objtbl.hidden = NO;
}
}
else if (sagmentController.selectedSegmentIndex == 1)
{
if ([z_paleo isEqualToString:#"0"]) {
[self getName:arrCatname];
objtbl.hidden = NO;
}
}
[objtbl reloadData];
}
-(void)getName:(NSMutableArray *)arr
{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < arr.count; i++)
{
NSString *string = [arr objectAtIndex:i];
dict = [[NSMutableDictionary alloc] init];
[dict setObject:string forKey:#"Name"];
[dict setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict];
}
[temp addObject:temp2];
sorted = [[NSArray alloc] initWithArray:temp];
}
-(void)getname2:(NSMutableArray *)array{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *string = [array objectAtIndex:i];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:string forKey:#"Name"];
[dict1 setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict1];
}
[temp addObject:temp2];
sorted1 = [[NSArray alloc] initWithArray:temp];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
int i = 0;
for(NSArray *array in sorted)
{
NSString *string = [array objectAtIndex:0];
if([string compare:title] == NSOrderedSame)
break;
i++;
}
return i;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (sagmentController.selectedSegmentIndex == 0) {
return [sorted count];
}else {
return [sorted count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *array = [sorted objectAtIndex:section];
return [array objectAtIndex:0];
//return [foodIndexTitles objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSMutableArray *titleArray = [NSMutableArray array];
[titleArray addObject:#"A"];
[titleArray addObject:#"B"];
[titleArray addObject:#"C"];
[titleArray addObject:#"D"];
[titleArray addObject:#"E"];
[titleArray addObject:#"F"];
[titleArray addObject:#"G"];
[titleArray addObject:#"H"];
[titleArray addObject:#"I"];
[titleArray addObject:#"J"];
[titleArray addObject:#"K"];
[titleArray addObject:#"L"];
[titleArray addObject:#"M"];
[titleArray addObject:#"N"];
[titleArray addObject:#"O"];
[titleArray addObject:#"P"];
[titleArray addObject:#"Q"];
[titleArray addObject:#"R"];
[titleArray addObject:#"S"];
[titleArray addObject:#"T"];
[titleArray addObject:#"U"];
[titleArray addObject:#"V"];
[titleArray addObject:#"W"];
[titleArray addObject:#"X"];
[titleArray addObject:#"Y"];
[titleArray addObject:#"Z"];
return titleArray;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (sagmentController.selectedSegmentIndex == 1) {
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}else{
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifire = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifire];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifire];
}
if (sagmentController.selectedSegmentIndex == 0) {
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Yes_check.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
}
else
{
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"No.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
return cell;
}
return cell;
}
I'm trying to get my contacts list in iOS to automatically add contacts to the contacts list without the user having to manually do it - similiar to how Whatsapp works. My code below simply shows prewritten values for the tableView and allows a bar button item to display the contacts list but not allow it to write any new entries to the tableView.
- (void)viewDidLoad
{
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
NSLog(#"phone:%#", phoneNumber);
}
}
self.friendsSearch.delegate = self;
self.friendsTableView.delegate = self;
self.friendsTableView.dataSource = self;
friendsListArray = [[NSMutableArray alloc] initWithObjects:
#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine",#"Ten", #"Eleven", nil];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0){
isFiltered = NO;
}
else
{
isFiltered = YES;
filterDataArray = [[NSMutableArray alloc]init];
for(NSString *str in friendsListArray){
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound){
[filterDataArray addObject:str];
}
}
}
[self.friendsTableView reloadData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.friendsSearch resignFirstResponder];
[self.view endEditing:YES];
}
// Table view datasource and delegate methods..
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFiltered){
return [filterDataArray count];
}
return [friendsListArray count];
return 1;
}
bool isKeyboardVisble = FALSE;
-(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];
}
if(!isFiltered){
cell.textLabel.text = [friendsListArray objectAtIndex:indexPath.row];
}
else //it is filtered
{
cell.textLabel.text = [filterDataArray objectAtIndex:indexPath.row];
}
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)backgroundClick:(id)sender {
[self.view endEditing:YES];
}
- (IBAction)addContact:(id)sender {
ABPeoplePickerNavigationController *peoplePicker =
[[ABPeoplePickerNavigationController alloc] init];
peoplePicker.peoplePickerDelegate = self;
[self presentModalViewController:peoplePicker animated:YES];
}
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)picker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
[self dismissModalViewControllerAnimated:YES];
return NO;
}
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)picker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier
{
return NO;
}
- (void)peoplePickerNavigationControllerDidCancel:
(ABPeoplePickerNavigationController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}
#end