How to print a phone number of a Contacts in table cell - ios

Check my Code:
#import "ContactViewController.h"
#import "SimpleTableCell.h"
#import Contacts;
#import ContactsUI;
#interface ContactViewController ()
#end
#implementation ContactViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_Contacts = [[NSMutableArray alloc]init];
_fullName = [[NSMutableArray alloc]init];
_phone = [[NSMutableArray alloc]init];
[self fetchContacts];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) fetchContacts
{
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;
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:#"acc_sett.png "];
}
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [label.value stringValue];
if ([phone length] > 0) {
NSMutableArray *cleanArray = [[NSMutableArray alloc] initWithCapacity:0];
// Here 'Activity' is your NSArray. A better name would be 'activity'
// (save capitalized names for classes)
for (NSString *item in contactNumbersArray)
{
[cleanArray addObject:[[item componentsSeparatedByString:#"-"] lastObject]];
}
NSLog(#"%#",cleanArray);
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage, nil];
[_Contacts addObject:personDict];
NSLog(#"%#",phone);
NSLog(#"%#",fullName);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.contacttableview reloadData];
});
}
}
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_Contacts count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary* personDict = [_Contacts objectAtIndex:indexPath.row];
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.Name.text = [personDict objectForKey:#"fullName"];
cell.Phone.text = [personDict objectForKey:#"phoneNumbers"];
cell.thumbnailImageView.image = [personDict objectForKey:#"userImage"];
NSData *dataItems=UIImageJPEGRepresentation(cell.thumbnailImageView.image, 0.1);
NSString *mysavedimage=#"userImage";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentDirectry=[path objectAtIndex:0];
NSString *fullpathfile=[DocumentDirectry stringByAppendingPathComponent:mysavedimage];
[dataItems writeToFile:fullpathfile atomically:YES];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"showDetail" sender:self];
}
#end
With the help of this code fullname and image of contacts person is coming on Table view but the Phone number is not coming and I am using a Custom Cell for the display of and one thing after fetching contacts from the simulator in console phone number and full name is both coming on console but on Table View Phone number is not coming.
May be I'm wrong somewhere. Please help, thank you in advance.

Try this:
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName", phone,#"phoneNumbers",profileImage,#"userImage" nil];
instead of:
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage, nil];
You are not updating the dictionary with required data.

Related

UITableView - How to delete file while deleting cell?

I'm trying to delete a csv file while deleting a cell, But I'm getting the next error when I pressed delete:
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 ..
2]'
* First throw call stack:
Code:
//
/
/ CameraViewController.m
// oFiOSstoryboard
//
// Created by Dorald on 24/05/15.
//
//
#import "CameraViewController.h"
#import "resultsDetailView.h"
#interface CameraViewController ()
#property (strong, nonatomic) IBOutlet UITableView *data;
#property (retain, nonatomic) IBOutlet UILabel *timeStamp;
#property (strong,nonatomic) NSMutableArray *dirList;
#property (nonatomic, assign) NSString *csvRow;
#property (nonatomic, strong) NSMutableArray *dataArray;
- (IBAction)didTapDeleteBtn:(id)sender;
#end
////////////////////////csv readder
NSMutableArray *tableDataArray;
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *strPath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"csv"];
NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
NSMutableArray *timeStampb = [[NSMutableArray alloc] init]; ;
NSMutableArray *arrayToDelete = [[NSMutableArray alloc] init]; ;
NSMutableArray *filePathsArray ;
//NSMutableArray *dirList= [[NSMutableArray alloc] init]; ;
NSString *currentcsvfile;
NSString *csvfilenameSave;
#implementation CameraViewController
#synthesize data;
- (void)viewDidLoad {
[super viewDidLoad];
// ////lista de documentos
self.data.scrollEnabled = YES;
self.data.delegate = self;
self.data.dataSource = self;
//filePathsArray =[[NSMutableArray alloc] init]; ;
self.data.allowsMultipleSelectionDuringEditing = YES;
self.dataArray = [[NSMutableArray alloc]init];
NSInteger count = 100;
for (NSInteger i = count; i>=0; i--) {
NSString *title = [NSString stringWithFormat:#"cell %ld",i];
[self.dataArray addObject:title];
}
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray* fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(#"\n File list %#",fileList);
//---- Sorting files by extension
NSMutableArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF EndsWith '.csv'"];
filePathsArray = [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(#"\n\n Sorted files by extension %#",filePathsArray);
self.dirList = [filePathsArray mutableCopy];
NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
if (!strFile) {
NSLog(#"Error reading file.");
}
[timeStampb release];
timeStampb = [[NSMutableArray alloc] initWithArray:[strFile componentsSeparatedByString:#"\,"]];
// this .csv file is seperated with new line character
// if .csv is seperated by comma use "," instesd of "\n"
for(NSString *countryname in timeStampb) {
NSLog(#"%#", timeStampb);
}
}
////////////////////////////////////////////////////////////////Delete csv files
//- (IBAction)delet:(id)sender {
// NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//
// NSString *filePath = [docPath stringByAppendingPathComponent:#"jorge.csv"];
// NSError *error = nil;
// [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
# pragma – mark table view DataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dirList count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIColor* color = [UIColor colorWithRed:(254.0/255.0) green:(251.0/255.0) blue:(248.0/255.0) alpha:1];
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:(253.0/255.0) green:(0.0/255.0) blue:(237.0/255.0) alpha:1];
[cell setSelectedBackgroundView:bgColorView];
cell.backgroundColor = color;
}
cell.textLabel.text = [timeStampb objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [self.dirList objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor colorWithRed:(0.0/255.0) green:(0.0/255.0) blue:(0.0/255.0) alpha:1];
cell.textLabel.font=[UIFont systemFontOfSize:8.0];
cell.detailTextLabel.font=[UIFont systemFontOfSize:15.0];
cell.detailTextLabel.textColor = [UIColor colorWithRed:(235.0/255.0) green:(120.0/255.0) blue:(33.0/255.0) alpha:1];
return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%d", indexPath.row);
currentcsvfile = [self.dirList objectAtIndex:indexPath.row ];;
csvfilenameSave = [NSString stringWithFormat:currentcsvfile];
NSArray *paths3 = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/currentcsvnamefile.txt",
documentsDirectory3];
//create content - four lines of text
NSString *content =csvfilenameSave;
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy error:nil];
[_dirList addObject:_dirList[indexPath.row]];
NSLog(#"\n current csv csvfilenameSave % ",csvfilenameSave);
//[self performSegueWithIdentifier:#"detailsegue" sender:self];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Update the delete button's title based on how many items are selected.
[_dirList removeObject:_dirList[indexPath.row]];
}
-(UITableViewCellEditingStyle)data:(UITableView *)data editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( editingStyle== UITableViewCellEditingStyleDelete) {
[self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[data setEditing:NO animated:YES];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingPathComponent:[self.dirList objectAtIndex:indexPath.row ]];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
[_dirList removeObjectAtIndex:indexPath.row];
}
}
#pragma mark - UITableView Delegate Methods
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
// return UITableViewCellEditingStyleDelete;
//}
#pragma mark - Delete Button Action
#pragma mark – TableView delegate
- (void)dealloc {
[_timeStamp release];
[self.dirList release];
self.data.delegate = nil;
self.data.dataSource = nil;
[super dealloc];
}
#end
Actually what you are doing you are removing the value from array at the top. You have to remove the value from array at the end of this function. As i have done in below code, please check my answer and use this code and then tell me if you face any issue. I Update my answer Please check it again.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( editingStyle== UITableViewCellEditingStyleDelete) {
currentcsvfile = [self.dirList objectAtIndex:indexPath.row];
csvfilenameSave = [NSString stringWithFormat:currentcsvfile];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingPathComponent:csvfilenameSave];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
[_dirList removeObjectAtIndex:indexPath.row];
[self.data beginUpdates];
[self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.data endUpdates];
[data setEditing:NO animated:YES];
}
}
Call to method [self.data deleteRowsAtIndexPaths:withRowAnimation:]; sends a message to the table view to adjust its presentation and thus tableview throws an NSInternalInconsistencyException because _dirList count is not equal to tableviews row count.
For details look at this article Inserting and Deleting Rows and Sections
You can handle this by removing the item corresponding to
the row from _dirList array at first and then sending deleteRowsAtIndexPaths:withRowAnimation: to the table view.
Try to replace below lines of code inside - (void)tableView:(UITableView *)tableView commitEditingStyle method:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( editingStyle== UITableViewCellEditingStyleDelete) {
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingPathComponent:[self.dirList objectAtIndex:indexPath.row ]];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
[_dirList removeObjectAtIndex:indexPath.row];
[self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
Hope it will work!

How to assign data from viewController to tableViewCell labels?

I have viewController with tableView, tableView has two prototype cells, second cell has sno, date, amount 3 labels. I created TableViewCell class and i created 3 outlets for this 3 labels in this TableViewCell class. I am getting data from server and i want to assign that data to this 3 labels. How?
In tableViewCell.h
#property (weak, nonatomic) IBOutlet UILabel *serialNumber;
#property (weak, nonatomic) IBOutlet UILabel *dateLabel;
#property (weak, nonatomic) IBOutlet UILabel *amountLabel;
In viewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.displayDataTableView.delegate = self;
self.displayDataTableView.dataSource = self;
self.urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
self.urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://"]];
self.dataTask = [self.urlSession dataTaskWithRequest:self.urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *serverRes = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// NSLog(#"...%# ", serverRes);
self.integer = [[serverRes objectForKey:#"Data"] count];
dispatch_async(dispatch_get_main_queue(), ^{
[self.displayDataTableView reloadData];
});
self.dateArray = [[NSMutableArray alloc]init];
self.amountArray = [[NSMutableArray alloc]init];
[self.dateArray addObject:[[[serverRes objectForKey:#"Data"] objectAtIndex:i] objectForKey:#"Date"]];
[self.amountArray addObject:[[[serverRes objectForKey:#"Data"] objectAtIndex:i] objectForKey:#"TotalAmount"]];
}
}];
[self.dataTask resume];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0)
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"detailsCell" forIndexPath:indexPath];
return cell;
}else{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"detailsTitle" forIndexPath:indexPath];
TableViewCell *tvc;
tvc.dateLabel.text = [self.dateArray objectAtIndex:indexPath.row];
NSLog(#"********** = %#", tvc.dateLabel.text);
return cell;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.displayDataTableView reloadData];
});
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
static NSString *cellIdentifier =#"detailsCell";
// Make Your cell as this
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.dateLabel.text = [self.dateArray objectAtIndex:indexPath.row];
cell.amountLabel.text = [self.amountArray objectAtIndex:indexPath.row];
}
return cell;
}
you need to change class of tableview cell
else{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"detailsTitle" forIndexPath:indexPath];
cell.dateLabel.text = [self.dateArray objectAtIndex:indexPath.row];
// same
cell.amountLabel.text = [self.dateArray objectAtIndex:indexPath.row];
NSLog(#"********** = %#", cell.dateLabel.text);
return cell;
}
or change sequence
self.dateArray = [[NSMutableArray alloc]init];
self.amountArray = [[NSMutableArray alloc]init];
[self.dateArray addObject:[[[serverRes objectForKey:#"Data"] objectAtIndex:i] objectForKey:#"Date"]];
[self.amountArray addObject:[[[serverRes objectForKey:#"Data"] objectAtIndex:i] objectForKey:#"TotalAmount"]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.displayDataTableView reloadData];
});
Use this code
self.dataTask = [self.urlSession dataTaskWithRequest:self.urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *serverRes = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.dateArray = [[NSMutableArray alloc]init];
self.amountArray = [[NSMutableArray alloc]init];
for (int i = 0; i < [[serverRes objectForKey:#"Data"] count]; i++) {
[self.dateArray addObject:[[[serverRes objectForKey:#"Data"] objectAtIndex:i] objectForKey:#"Date"]];
[self.amountArray addObject:[[[serverRes objectForKey:#"Data"] objectAtIndex:i] objectForKey:#"TotalAmount"]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.displayDataTableView reloadData];
});
}];

array data from json duplicated on tableview ios

i'm displaying data from a webservice in my tableview app but i get the array twice in the tableview.
also i'm trying to use the endless scroll to show paginated data without success
(void)viewDidLoad {
[super viewDidLoad];
self.articlesArray = [[NSMutableArray alloc] init];
[self fetchData:1];
}
my function to fetch data
-(void) fetchData:(int)page {
NSString *urlString = [NSString
stringWithFormat:#"http://url?page=%d", (int)page];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
NSData *theData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
self.articlesArray = [NSJSONSerialization JSONObjectWithData:theData
options:NSJSONReadingMutableContainers
error:nil];
[self.tableView registerNib:[UINib nibWithNibName:#"ArticleCell" bundle:nil] forCellReuseIdentifier:#"ArticleCell"];
}
and here's my tableview methods please see what i did wrong
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section==0)
{
return [self.articlesArray count];
else
return [self.articlesArray count];
}
// return [self.articlesArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
if (3 == (row % 4)) { // or 0 == if you want the first cell to be an ad!
static NSString *MyIdentifier = #"AdCell";
AdViewCell *cell = (AdViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if ((cell == nil) || (![cell isKindOfClass: AdViewCell.class]))
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AdCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell = [[AdViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] ;
}
GADBannerView *bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeMediumRectangle];
bannerView.adUnitID =#"";
bannerView.rootViewController =self;
GADRequest *request = [GADRequest request];
[bannerView loadRequest:request];
[cell.contentView addSubview:bannerView];
return cell;
}
else{
static NSString *simpleTableIdentifier = #"ArticleCell";
ArticleViewCell *cell = (ArticleViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
if ((cell == nil) || (![cell isKindOfClass: ArticleViewCell.class]))
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ArticleCell" owner:self options:nil];
cell = [nib objectAtIndex:1];
cell = [[ArticleViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleTableIdentifier] ;
}
NSDictionary * tempDictionary = [self.articlesArray objectAtIndex:indexPath.row];
NSString *imageUrl = [[self.articlesArray objectAtIndex:indexPath.row]objectForKey:#"featured_image"];
imageUrl = [imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[cell.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl ] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image){
// Set your image over here
}else{
//something went wrong
NSLog(#"Error occured : %#", [error description]);
}
}];
NSString * title=[tempDictionary valueForKeyPath:#"title.rendered"];
cell.titleLabel.text = title;
return cell;
}
}
You can remove duplicate values once you get response from json, before reload tableview remove duplicate elements from array
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:YourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
Thanks

Using NSMutableArray in TableViewController with JSON data

Good afternoon,
I'm trying to use a NSMutableArray in my TableViewController from a JSON output and I'm a little bit lost because currently I can store my JSON data in a NSMutableArray, and I have checked with a NSLog that the content is OK, but now I have to show that data in my TableViewController and that's when I'm lost.
I'm using an another example of TableViewController using NSArray but now I have to modify it for a NSMutableArray. If you can help me with some code or show me some examples or tutorials I will be much appreciated.
I know in my code maybe I have something wrong because I'm using an old example using only NSArray but I'm showing you because that's what I don't know how to do, I need to work with NSMutableArray and that's why I'm asking for your help.
How can I show a NSMutableArray in my TableViewController?
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
//NSError * error;
//NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
//self.carModels = [[NSMutableArray alloc] init];
NSMutableArray *carModels=[[NSMutableArray alloc]init];
NSMutableArray *carMakes=[[NSMutableArray alloc]init];
NSMutableArray *carImages=[[NSMutableArray alloc]init];
#try
{
NSError *error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error)
{
NSLog(#"%#",[error localizedDescription]);
}
else
{
for(int i=0;i<json.count;i++)
{
NSDictionary * jsonObject = [json objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[carImages addObject:imagen];
NSDictionary * jsonObject2 = [json objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[carMakes addObject:user];
NSDictionary * jsonObject3 = [json objectAtIndex:i];
NSString* images = [jsonObject3 objectForKey:#"date"];
[carModels addObject:images];
}
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
}
#finally
{
NSLog(#"finally");
// That's showing the data "1, 2, 3".
NSLog(#"models: %#", carModels);
NSLog(#"makes: %#", carMakes);
NSLog(#"images: %#", carImages);
}
}
);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.carModels count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [_carMakes objectAtIndex: [indexPath row]];
cell.modelLabel.text = [self.carModels objectAtIndex:[indexPath row]];
UIImage *carPhoto = [UIImage imageNamed: [self.carImages objectAtIndex: [indexPath row]]];
cell.carImage.image = carPhoto;
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ShowCarDetails"])
{
CarDetailViewController *detailViewController =
[segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView
indexPathForSelectedRow];
detailViewController.carDetailModel = [[NSArray alloc]
initWithObjects: [self.carMakes
objectAtIndex:[myIndexPath row]],
[self.carModels objectAtIndex:[myIndexPath row]],
[self.carImages objectAtIndex:[myIndexPath row]],
nil];
}
}
Thanks.
Declare NSMutableArray *jsonArray ; as global
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
//NSError * error;
//NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
//self.carModels = [[NSMutableArray alloc] init];
#try
{
NSError *error;
[jsonArray removeAllObjects];
jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
}
#finally
{
[self.tableView reloadData]
}
}
);
}
To Display The TableView Like This
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jsonArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [[jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"];
cell.modelLabel.text = [[jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
UIImage *carPhoto = [[jsonArray objectAtIndex:indexPath.row] valueForKey:#"date"];
cell.carImage.image = carPhoto;
return cell;
}
Add
[self.tableView reloadData]
after you have fetched and parsed the JSON.
Whenever you change table datas from different array just add [self.tableView reloadData] in you method.
It will remove old data & shows new data into your tableview.

NSInvalidArgumentException reason: data parameter is nil in UITableView while trying to display the Flickr images

Hi in my application I want to display the Flickr album list in UITableView so i have searched for long time and i have found some solution. I have used the method which given in the solution its not working its giving error like
NSInvalidArgumentException', reason: 'data parameter is nil
The solution link click here
And since I'm trying this for first time I'm not able resolve this issue. This is MY API LINK for Flickr
I have used this code to display the Flickr image Album list in UItableview
{
NSMutableArray *photoURLs;
NSMutableArray *photoSetNames;
NSMutableArray *photoid1;
}
My Flickr API key
#define FlickrAPIKey #"a6a0c7d5efccffc285b0fe5ee1d938e3"
- (void)viewDidLoad
{
[super viewDidLoad];
photoURLs = [[NSMutableArray alloc] init];
photoSetNames = [[NSMutableArray alloc] init];
photoid1 = [[NSMutableArray alloc] init];
[self loadFlickrPhotos];
}
My TableView code
- (void)loadFlickrPhotos
{
NSString *urlString = [NSString stringWithFormat:#"http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=%#&user_id=%#&per_page=10&format=json&nojsoncallback=1", FlickrAPIKey, #"124757153#N04"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *photoid = [photoset objectForKey:#"id"];
[photoid1 addObject:photoid];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [photoSetNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier =#"Cell";
flickrpoliticalCell *cell =(flickrpoliticalCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[flickrpoliticalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.tit.text = [photoSetNames objectAtIndex:indexPath.row];
return cell;
}
try this
- (void)loadFlickrPhotos
{
//
NSString *urlString = [NSString stringWithFormat:#"https://www.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=a6a0c7d5efccffc285b0fe5ee1d938e3&format=json&user_id=124757153#N04&per_page=10&nojsoncallback=1",nil];
NSLog(#"the url string==%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"the str==%#",jsonString);
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
NSLog(#"title==%#",title);
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *primary = [photoset objectForKey:#"primary"];
NSString *server = [photoset objectForKey:#"server"];
NSString *secret = [photoset objectForKey:#"secret"];
NSString *farm = [photoset objectForKey:#"farm"];
NSString *urlstr=[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg",farm,server,primary,secret];
NSLog(#"your photo id==%#",urlstr);
[photoids addObject:urlstr];
}
}

Resources