How can I import all the contacts from the phone book in your application. and so that we could gain the imported contacts.
Andrei brother if you have not got answer still,I give you answer.I tried and got the solution.It works fine.
The AddressBookUI framework is deprecated in iOS 9, so we need to use Contact Framework.
First I set or hook up the tableView using XIB or Storyboard for showing contacts.
Must import the Contacts framework
ViewController.h
#import <UIKit/UIKit.h>
#import <Contacts/Contacts.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
}
#property (strong, nonatomic) IBOutlet UITableView *tableViewShowContacts;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrayContacts;
}
#end
#implementation ViewController
#synthesize tableViewShowContacts;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayContacts = [[NSMutableArray alloc]init];
[self getAuthorizationandContact];
//Register the cell
[tableViewContactData registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
[self.view addSubview:tableViewShowContacts];
}
-(void)fetchContactsandAuthorization
{
// Request authorization to Contacts
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES)
{
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
for (CNContact *contact in cnContacts)
{
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"person-icon.png"];
}
for (CNLabeledValue *label in contact.phoneNumbers)
{
phone = [label.value stringValue];
if ([phone length] > 0) {
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage,#"userImage",phone,#"PhoneNumbers", nil];
[arrayContacts addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
NSLog(#"The contacts are - %#",arrayContacts);
}
dispatch_async(dispatch_get_main_queue(), ^{
[tableViewShowContacts reloadData];
});
}
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayContacts.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
cell.textLabel.text = arrayContacts[indexPath.row];
return cell;
}
The printed results of Contacts are
The contacts are - (
"John Appleseed",
"Kate Bell",
"Anna Haro",
"Daniel Higgins",
"David Taylor",
"Hank Zakroff"
)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i have following code in viewdidload
totalstring=[[NSMutableArray alloc]initWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"n",#"o",#"p",#"q",#"r",#"s",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z", nil];
indid=indidvalue1;
NSLog(#"the ind id value is %#",indid);
serviceCall=[[Services alloc]init];
NSString *contactsDisplay1=#"ContactDetails";
NSDictionary *contactsDisplayDetails1 =#{#"IND_ID":indid};
[serviceCall ContactsDisplayUrl:contactsDisplay1 ContactsDisplayDetails:contactsDisplayDetails1];
[serviceCall setDelegate:self];
code for implimenting search bar
{
filteredstring =[[NSMutableArray alloc]init];
for (NSString *str in totalstring )
{
NSRange stringrange =[str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringrange.location!= NSNotFound)
{
[filteredstring addObject:str];
}
}
}
[tableView reloadData];
code for table view
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [searchResultsArray objectAtIndex:indexPath.row];
} else
{
UIFont *myfont=[UIFont fontWithName:#"Arial" size:35];
cell.textLabel.text = [contactNameSplitDisplayArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[relationTypeSplitDisplayArray objectAtIndex:indexPath.row];
cell.textLabel.font=myfont;
}
return cell;
How can i implement search bar in table view for contacts in story board ?I am new to iOS
?
and how to implement plus button and dots button within the table view?
Devi my complete answer.It works perfectly.I use search bar.Also use that delegate methods.
ViewController.h
#import <UIKit/UIKit.h>
#import <Contacts/Contacts.h> //Must import contact framework
#interface ViewController : UIViewController<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UISearchBar *searchbarContacts;
#property (strong, nonatomic) IBOutlet UITableView *tableViewContactData;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrayTableData;
NSMutableArray *arraySearchContactData;
}
#end
#implementation ViewController
#synthesize tableViewContactData;
#synthesize searchbarContacts;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayTableData = [[NSMutableArray alloc]init];
arraySearchContactData = [[NSMutableArray alloc]init];
[self fetchContactsandAuthorization];
[tableViewContactData registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
[self.view addSubview:tableViewContactData];
}
//Fetching Contact and Authorization access
-(void)fetchContactsandAuthorization
{
// Request authorization to Contacts
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
for (CNContact *contact in cnContacts)
{
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"person-icon.png"];
}
for (CNLabeledValue *label in contact.phoneNumbers)
{
phone = [label.value stringValue];
if ([phone length] > 0) {
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage,#"userImage",phone,#"PhoneNumbers", nil];
[arrayTableData addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
[arraySearchContactData addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
NSLog(#"The contactsArray are - %#",arrayTableData);
}
dispatch_async(dispatch_get_main_queue(), ^{
[tableViewContactData reloadData];
});
}
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayTableData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
cell.textLabel.text = arrayTableData[indexPath.row];
return cell;
}
#pragma mark - SearchBar Delegate Methods
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
#try
{
[arrayTableData removeAllObjects];
stringSearch = #"YES";
NSString *name = #"";
if ([searchText length] > 0)
{
for (int i = 0; i < [arraySearchContactData count] ; i++)
{
name = [arraySearchContactData objectAtIndex:i];
if (name.length >= searchText.length)
{
NSRange titleResultsRange = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
{
[arrayTableData addObject:[arraySearchContactData objectAtIndex:i]];
}
}
}
}
else
{
[arrayTableData addObjectsFromArray:arraySearchContactData];
}
[tableViewContactData reloadData];
}
#catch (NSException *exception) {
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)SearchBar
{
SearchBar.showsCancelButton=YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)theSearchBar
{
[theSearchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)SearchBar
{
#try
{
SearchBar.showsCancelButton=NO;
[SearchBar resignFirstResponder];
[tableViewContactData reloadData];
}
#catch (NSException *exception) {
}
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)SearchBar
{
[SearchBar resignFirstResponder];
}
#end
The Printed results For Contacts
The contactsArray are - (
"John Appleseed",
"Kate Bell",
"Anna Haro",
"Daniel Higgins",
"David Taylor",
"Hank Zakroff"
)
Please Refer the below link, i can able to implement the search bar in table view by using this.
http://www.appcoda.com/search-bar-tutorial-ios7/
In my app I need to display all contacts from the device in a custom table viewcontoller when I click contacts button. I found a lot of demos using addressbook framework but in it the contacts are displayed in default device format using ABPeoplePickerNavigationController. But I need to display all contacts in custom view. Is there any way to do that. Also my app should work in iOS7 and above. Can Contacts Framework be used in iOS 7 and 8? I'm using xcode 7.2. Please provide the solutions in objective C as I'm not familier with swift.Thanks in advance.
In iOS 9 AddressBook Framework is deprecated.Kindly use Contact framework.
I tried, and it works fabulously.
Very Perfect answer is below.
#import "ViewController.h"
#import <Contacts/Contacts.h>
#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITableView *tableViewContactData;
NSMutableArray *arrayTableData;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayTableData = [[NSMutableArray alloc]init];
[self fetchContactsandAuthorization];
tableViewContactData = [[UITableView alloc] init];
tableViewContactData.frame = CGRectMake(0, 50, 320, 518);
tableViewContactData.delegate = self;
tableViewContactData.dataSource = self;
[tableViewContactData registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
[self.view addSubview:tableViewContactData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//UITAbleView Deleate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayTableData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
cell.textLabel.text = arrayTableData[indexPath.row];
return cell;
}
//This is for fetching contacts from iPhone.Also It asks authorization permission.
-(void)fetchContactsandAuthorization
{
// Request authorization to Contacts
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES)
{
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error)
{
NSLog(#"error fetching contacts %#", error);
}
else
{
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
for (CNContact *contact in cnContacts) {
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"person-icon.png"];
}
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [label.value stringValue];
if ([phone length] > 0) {
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage,#"userImage",phone,#"PhoneNumbers", nil];
[arrayTableData addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
NSLog(#"The contactsArray are - %#",arrayTableData);
}
dispatch_async(dispatch_get_main_queue(), ^{
[tableViewContactData reloadData];
});
}
}
}];
}
#end
The output is
The contactsArray are - (
"John Appleseed",
"Kate Bell",
"Anna Haro",
"Daniel Higgins",
"David Taylor",
"Hank Zakroff"
}
Simple using address book framework,
just follow the link
Use this link
I am having trouble getting my UITableView to reload appropriately. My app sometime works and other times it crashes because one of the data elements is not properly stored in an array when the tableView tries to update. Can someone point me out the proper place to reload my tableView please.
- (void)viewDidLoad {
[super viewDidLoad];
[self queryForNewBooks];}
-(void)queryForNewBooks{
_bookNameArray = [[NSMutableArray alloc] init];
_authorNameArray = [[NSMutableArray alloc] init];
_isbnNumberArray = [[NSMutableArray alloc] init];
_bookImageData = [[NSMutableArray alloc] init];
PFQuery *query = [PFQuery queryWithClassName:#"BooksForSale"];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^( NSArray *objects, NSError *error) {
if (objects.count >=1) {
for (PFObject *object in objects) {
PFFile *imageFile = [object objectForKey:#"image"];
[imageFile getDataInBackgroundWithBlock:^(NSData *result, NSError *error) {
if (!error) {
NSData *data = result;
NSLog(#"HEYYYYYY");
if (data == NULL) {
}
else{
[ _bookImageData addObject:data];
//I have tried placing it here [self.tableView reloadData]
// NSLog(#"%#",[_bookImageData objectAtIndex:0]);
}
}
}
];
NSDictionary *bookNameDictionary = object[#"nameOfBook"];
NSDictionary *authorNameDictionary = object[#"Author"];
NSDictionary *bookImageDictionary = object [#"image"];
NSDictionary *isbnNumberDictionary = object [#"isbnNumber"];
NSString *objectID = [object objectId];
if (bookNameDictionary != NULL){
NSLog(#"Yo bro here is the book name %#",bookNameDictionary);
[_bookNameArray addObject:bookNameDictionary];
NSLog(#"number: %#", bookNameDictionary);
}
if (bookNameDictionary == NULL) {
[_bookNameArray addObject:#""];
NSLog(#"Blank space");
}
if (authorNameDictionary != NULL) {
[_authorNameArray addObject:authorNameDictionary];
// [_tableData addObject:ft];
NSLog(#"Author Name : %#",_authorNameArray);
// NSLog(#"the table data is %#",_tableData);
}
if (authorNameDictionary == NULL) {
[_authorNameArray addObject:#""];
NSLog(#"Blank space");
}
if (isbnNumberDictionary != NULL){
NSLog(#"Yo bro here is the isbn %#",isbnNumberDictionary);
[_isbnNumberArray addObject:isbnNumberDictionary];
NSLog(#"number: %#", isbnNumberDictionary);
//[self.tableview reloadData];
}
if (isbnNumberDictionary == NULL) {
[_isbnNumberArray addObject:#""];
NSLog(#"Blank space");
}
/* if (bookImageDictionary !=NULL){
[_bookImageData addObject:bookImageDictionary];
}
if (bookImageDictionary ==NULL){
[_bookImageData addObject:#""];
NSLog(#"Blank Space");
}*/
if (objectID != NULL) {
[_objectIDArray addObject:objectID];
NSLog(#"object id is : %#",objectID);
}
if (objectID ==NULL){
[_objectIDArray addObject:#"blank"];
}
}
}
// code
}];
//I have tried placing it here [self.tableView reloadData]
);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.bookNameArray count];
}
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TableViewCell";
TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSLog(#"Here are the book names, %#",_bookNameArray);
cell.bookNameLabel.text = [_bookNameArray objectAtIndex:indexPath.row];
cell.authorNameLabel.text = [_authorNameArray objectAtIndex:indexPath.row];
if ([_bookImageData objectAtIndex:indexPath.row] != NULL ) {
NSLog(#"it seems to work");
UIImage *image = [UIImage imageWithData: [_bookImageData objectAtIndex:indexPath.row]];
cell.bookImageLabel.image = image;
}
else{
NSLog(#"Error");
}
return cell;
}
Updating question:
Is this the proper way to declare a PFimageView?
Can I just drag a UIImageView in the Xib file and then
change its class to PFImageView?
After changing it to a PFImageView should I be able to just link the view to the outlet as normally done?
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import <ParseUI/ParseUI.h>
#interface TableViewCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *bookNameLabel;
#property (nonatomic, weak) IBOutlet UILabel *authorNameLabel;
#property (nonatomic, weak) IBOutlet PFImageView *bookImageLabel;
#property (nonatomic, weak) IBOutlet UILabel *priceOfBook;
#end
#import <Parse/Parse.h>
#import "TableViewCell.h"
#import <ParseUI/ParseUI.h>
#implementation TableViewCell
#synthesize bookNameLabel =_bookNameLabel;
#synthesize authorNameLabel = _authorNameLabel;
#synthesize bookImageLabel = _bookImageLabel;
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
The part that complicates the code is the need to fetch images using the objects returned by the query. The simplest solution is to omit the image fetching from the query completion handler.
Instead, loop the returned objects, building the arrays (there's room for improvement here, too, but just sticking with the crash part of your problem for now). In the _bookImageData array, don't try to keep images, instead keep the PFFile for each object...
// in the loop of objects, omit getDataInBackground and just do...
[_bookImageData addObject:object[#"image"]];
The answer to the stated question -- where to reload the table -- is after the loop that builds the table datasource.
for (PFObject *object in objects) {
// code to build all of the arrays, omitting getDataInBackground
// ...
}
[self.tableView reloadData];
In your table view cell, replace the image view with a PFImageView, because it can take care of fetching the image data for you (and other useful stuff like cacheing it). Your cellForRowAtIndexPath: will then look like this...
// bookImageLabel must be a PFImageView
// remember, we put the PFFile for each object into the _bookImageData array
cell.bookImageLabel.file = _bookImageData[indexPath.row];
[cell.bookImageLabel loadInBackground];
I have a view controller that retrieves address information from my web service, stores it in a mutable array and then displays each address in a table view. I have a search bar on the same view controller that i'd like to search through each of the addresses and display the results. I have this working with a test NSArray, however I'm not sure what I need to do to the filterContentForSearchText function to get it to search through an NSMutableArray. Any help appreciated.
Object Class
// Branches.h
#interface Branches : NSObject
#property (nonatomic, retain) NSString *BranchAddress;
#end
View Controller Class
// ViewController.h
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
.
// ViewController.m
#import "AFHTTPRequestOperationManager.h"
#import "ViewController.h"
#import "Branches.h"
#interface ViewController () {
NSMutableArray *array;
}
#property (strong, nonatomic) NSArray *searchResults;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize myArray
array = [[NSMutableArray alloc] init];
// Set POST parameters
NSDictionary *parameters = #{#"key" : #"value"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"webservice_address" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Check to see if responseObject contains data
if (responseObject != nil) {
// Loop through JSON
for (NSDictionary *dictionary in responseObject) {
// Initialize object
Branches *branches = [[Branches alloc] init];
branches.branchAddress = [dictionary objectForKey:#"Object"];
// Add object to myArray
[array addObject:branches];
[self.tableView reloadData];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
#pragma Table View Methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [self.searchResults count];
} else {
return [array count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [[array objectAtIndex:indexPath.row] BranchAddress];
}
return cell;
}
#pragma Search Methods
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSArray *masterArray = array;
NSArray *searchResults = [masterArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Branches *evaluatedObject, NSDictionary *bindings) {
//NSLog(#"%#", evaluatedObject.BranchAddress);
return ([evaluatedObject.BranchAddress rangeOfString: searchText options:NSCaseInsensitiveSearch].location != NSNotFound);
}]];
NSLog(#" %i", searchResults.count);
//[searchResults removeAllObjects];
//[searchResults addObjectsFromArray:searchResults];
//reload after this
NSLog(#"%#", [searchResults objectAtIndex:0]);
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#end
u can try this
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSArray *masterArray = self.array;
NSArray *resultsArray = [masterArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Branches *evaluatedObject, NSDictionary *bindings) {
return ([evaluatedObject.BranchAddress rangeOfString: searchText options:NSCaseInsensitiveSearch].location != NSNotFound);
}]];
//edited
[self.searchResults removeAllObjects]; //self.searchResults should be mutable array
[self.searchResults addObjectsFromArray:resultsArray];//put the new values to searchResults
//after this self.searchResults contains objects of filtered Branches u can get the values for example
NSLog(#"%#", [[self.searchResults objectAtIndex:0] BranchAddress]);//self.searchResults contains objects of Branches not the string itself
//reload after this
}
I am currently trying to display a NSMutableArray into a UITableView. The problem lies in the NumberOfRowsInSection and in the CellForRowAtIndex. I am able to fetch twitter feed and logic to the console, but I can't seem to display it to my UITable view. What could be the reason?
#import "ViewController.h"
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#import "TwitterPostInfo.h"
#import "CustomCell.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
twitterPosts = [[NSMutableArray alloc]init];
[self refreshTwitter];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)refreshTwitter
{
ACAccountStore *accountStore = [[ACAccountStore alloc]init];
if (accountStore != nil)
{
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
if (accountType != nil)
{
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if (granted)
{
//Succesful Access
NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];
if (twitterAccounts != nil)
{
ACAccount *currentAccount = [twitterAccounts objectAtIndex:0];
if (currentAccount != nil)
{
NSString *requestString = #"https://api.twitter.com/1.1/statuses/user_timeline.json";
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:requestString] parameters:nil];
[request setAccount:currentAccount];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ((error == nil) && ([urlResponse statusCode] == 200))
{
NSArray *twitterFeed = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
// loop throught all posts
for (NSInteger i=0; i<[twitterFeed count]; i++)
{
TwitterPostInfo *postInfo = [self createPostInfoFromDictionary:[twitterFeed objectAtIndex:i]];
if (postInfo != nil)
{
[twitterPosts addObject:postInfo];
}
}
}
}];
}
}
}
else
{
//Access Denied
}
}];
}
}
}
-(TwitterPostInfo*)createPostInfoFromDictionary:(NSDictionary*)postDictionary
{
NSString *timeDateString = [postDictionary valueForKey:#"created_at"];
NSDictionary *userDictionary = [postDictionary objectForKey:#"user"];
NSString *userString = [userDictionary valueForKey:#"screen_name"];
NSString *userDesc = [userDictionary valueForKey:#"description"];
NSString *tweetText = [postDictionary valueForKey:#"text"];
TwitterPostInfo *postInfo = [[TwitterPostInfo alloc]initWithPostInfo:userString userDesc:userDesc text:tweetText timeDateInfo:timeDateString];
return postInfo;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [twitterPosts count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CloneCell"];
if (cell != nil)
{
// ISSUE BEGINS HERE
//TwitterPostInfo *postInfo = (TwitterPostInfo*) twitterPosts[indexPath.row];
//cell = [twitterPosts objectAtIndex:indexPath.row];
cell.textLabel.text = [twitterPosts objectAtIndex:indexPath.row];
}
return cell;
}
#end
The post about the valid cell object is important, but your real problem here is that you are assigning an object of type TwitterPostInfo to cell.textLabel.text, which is an NSString.
If what you're trying to display is the text of the Tweet, you'll want something more like this:
TwitterPostInfo *postInfo = (TwitterPostInfo*) twitterPosts[indexPath.row];
cell.textLabel.text = postInfo.text; //or however your getter for the text is implemented
If you're trying to display all of the information of the Tweet in the cell, you're going to have to create your own custom cell and then assign each UILabel in the cell to the different properties stored in the TwitterPostInfo object.
dequeueReusableCellWithIdentifier: may return nil. In this case, you need to create a proper UITableViewCell yourself.
Try creating a cell if it is nil. Always make sure to return a valid cell object.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CloneCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] init];
}
cell.textLabel.text = [twitterPosts objectAtIndex:indexPath.row];
return cell;