After successfully getting the text to work on my UITableView, I still have not got the images working. It seems that the LogoURL array is blank on UITableViewCellsForRow, here is my code.
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) MSTable *table;
#property (nonatomic, strong) NSMutableArray *items;
#property (weak, nonatomic) IBOutlet UITableView *MainTableView;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// create the activity indicator in the main queue
self.MainTableView.hidden = YES;
UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:ac];
[ac startAnimating];
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
self.table = [self.client tableWithName:#"notifications"];
self.rowitems = [[NSMutableArray alloc] init];
MSQuery *query = [self.table query];
query.fetchLimit = 3;
[query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error)
{
self.rowitems = [items mutableCopy];
[self.MainTableView reloadData];
self.MainTableView.hidden = YES;
int a;
for (a = 0; a < 3; a++)
{
NSDictionary *apt = [self.rowitems objectAtIndex:a];
NSLog(#"%#", apt[#"barID"]);
NSDictionary *barIDDictionary = #{ #"myParam": apt[#"barID"]};
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
[self.client invokeAPI:#"photos" body:barIDDictionary HTTPMethod:#"POST" parameters:nil headers:nil completion:^(id result, NSHTTPURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Error %#", error );
}
else {
NSString *string = [NSString stringWithFormat:#"%#", [result objectForKey:#"rows"]];
NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *newStr = [completion substringFromIndex:1];
NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
[self.logoURL addObject:finalstring];
NSLog(#"%#",finalstring);
[self.MainTableView reloadData];
self.MainTableView.hidden = NO;
}
}];
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.rowitems count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
NSDictionary *stress = [self.rowitems objectAtIndex:indexPath.row];
cell.textLabel.text = stress[#"content"];
switch (indexPath.row) {
case 0:
[cell.imageView setImageWithURL:[NSURL URLWithString:[self.logoURL objectAtIndex:(1)]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
NSLog(#"%#", [self.logoURL objectAtIndex:(1)]);
break;
case 1:
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
case 2:
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
}
return cell;
}
#end
As you can see on the first case statement, I have tried to see if I can see the array contents and I cannot. Any help would be fab - I am sure its to do with where I put my reload table but again I am unsure.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
NSDictionary *stress = [self.rowitems objectAtIndex:indexPath.row];
cell.textLabel.text = stress[#"content"];
switch (indexPath.row) {
case 0:
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#"]]]];
NSLog(#"%#", [self.logoURL objectAtIndex:(1)]);
break;
case 1:
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#"]]]];
break;
case 2:
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#"]]]];
break;
}
return cell;
}
Related
I have a base url and I have the image names in a array extracted from there server .I am using a collection view, I have to display all the 23 images in the collection view I have two problems
when I try to access cell.imageview.image it says no property image view in cell but in custom cell.h file I have created the outlet and I am using storyboard
2.as one is string base url and other end path or filename of the images in array extracted from john from server
this is how I get from data--
{
"added_by" = 1;
"category_id" = 182;
"category_image" = "shots.png";
"category_name" = Shots;
sequance = 19;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 168;
"category_image" = "classiccocktail.png";
"category_name" = "Classic Cocktails";
sequance = 20;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 167;
"category_image" = "sprit.png";
"category_name" = "Non Alcoholic Bevereges";
sequance = 21;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 162;
"category_image" = "nonalcoholic.png";
"category_name" = "Non Alcoholic Coolers";
sequance = 22;
status = 0;
"store_id" = 1;
}
this is nslog of server reply
This is the slog of the array in which I have stored the data
2017-06-13 10:16:39.181 MenuBar[1703:94836] (
"kinfisherultra.png",
"impotedbeernew.png",
"blendedwhiskyne.png",
"johywalkerbluee.png",
"singlemaltnew.png",
"americanwishkynew.png",
"irishwishkynew.png",
"Belvedere-Vodka.png",
"Ginnew.png",
"Tequilanew.png",
"rumnew.png",
"amarula.png",
"aprities.png",
"breezernew1.png",
"conganbrndynew.png",
"wine&sparkling.png",
"bottels.png",
"cocktailpitchers.png",
"mocktails.png",
"shots.png",
"classiccocktail.png",
"sprit.png",
"nonalcoholic.png"
)
and I have a base url how to get all these images in collection view?
this is customcell.h file
#import <UIKit/UIKit.h>
#interface CustomCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UILabel *lbl;
#end
customcell.h file
#import "CustomCell.h"
#implementation CustomCell
-(void)awakeFromNib {
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onButtonTapped:)];
[tap setNumberOfTapsRequired:1];
[self addGestureRecognizer:tap];
[super awakeFromNib];
}
-(void)onButtonTapped:(id)sender
{
//the response to the gesture.
//mind that this is done in the cell. If you don't want things to happen from this cell.
//then you can still activate this the way you did in your question.
}
#end
view controller.hfile
if(!sharedSessionMainQueue){
sharedSessionMainQueue = [NSURLSession sessionWithConfiguration:nil delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
}
[[sharedSessionMainQueue dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSDictionary *temp=jsonDict;
NSLog(#"Req cust:%#",requestReply);
NSLog(#"requestReply cust liqour category: %#", jsonDict);
NSArray *imgNameArray = [temp valueForKey: #"category_name"];
NSLog(#"$$$%#$$$",imgNameArray);
self.iname=[jsonDict valueForKey:#"category_image"];
NSLog(#"%#",self.iname);
//[self imagedl];
NSDictionary *tempz=[jsonDict valueForKey:#"category_name"];
Photos = [NSArray arrayWithObjects:#"http://test.kre8tives.com/barebones/upload/%#",self.iname, nil];
NSLog(#"^^^%#",tempz);
//NSLog(#"$$%#",[Photos objectAtIndex:]); //Here can show Img's values correctl
// }
// self.recipeImageView.image = [UIImage imageNamed:self.recipeImageName];
}] resume];
_barbutton.target = self.revealViewController;
_barbutton.action = #selector(revealToggle:);
//[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background"]];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)geti{
NSString *temps= [NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/%#",self.iname];
UIImage *temp;
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:temps]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"%#",response);
//temp.image= [UIImage imageWithData:data];
}];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 23;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//[CustomCell registerClass:[CustomCell class] forCellWithReuseIdentifier:reuseIdentifier];
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
[[[cell contentView] subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
UIView * contents=[[UIView alloc] initWithFrame:cell.contentView.bounds];
[contents setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:contents];
_imageView.image;
// set tag to the indexPath.row so we can access it later
[cell setTag:indexPath.row];
// add interactivity
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onButtonTapped:)];
[tap setNumberOfTapsRequired:1];
[cell addGestureRecognizer:tap];
NSString *fileName = [NSString stringWithFormat:#"%#",self.iname]; //objectAtIndex:indexPath];
NSLog(#"%#",fileName);
NSString *baseurl=[NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/"];
NSDictionary *doors = [NSMutableArray new];
NSString *base=[NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/"];
NSLog(#"%#",doors);
NSString *path = [NSString stringWithFormat:#"%#/%#", baseurl, _iname];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgage = [[UIImage alloc] initWithData:data];
//NSString *filePath = [baseurl stringByAppendingPathComponent:fileName];
NSDictionary *dict = self.iname[indexPath.row];
NSLog(#"%#", [self.iname objectAtIndex: indexPath.row]);
NSString *filePath=[NSString stringWithFormat:#"%#%#",baseurl,fileName];
NSString *paths = [NSString stringWithFormat:#"%#/%#", baseurl, [[dict valueForKey:#"category_image"] objectAtIndex: indexPath.row]];
NSLog(#"%#",dict);
NSString *temps= [NSString stringWithFormat:#"%#",filePath];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:paths]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"%#",response);
UIImage *imgage = [[UIImage alloc] initWithData:data];
_imageView.image=[[UIImage alloc] initWithData:imgage];
_imageView.image=[[NSData alloc]initWithData:data];
//imageView.contentMode = UIViewContentModeScaleAspectFill;
// _imageView.clipsToBounds = YES;
//imageView.tag = IMAGE_VIEW_TAG;
}];
if (cell.selected) {
cell.backgroundColor = [UIColor blueColor]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}
Register your custom cell in viewDidLoad method
[yourCollectionView registerNib:[UINib nibWithNibName:#"CustomCell" bundle:nil] forCellWithReuseIdentifier:#"your Cell Identifier"];
And then you will write on cellForItemAtIndexPath method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"your Cell Identifier";
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSDictionary *dict = imageAry[indexPath.row];
//SdWebimage to load image
[cell.imgUser sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", baseUrl, dict[#"imageName"]]];
return cell;
}
Download SDWebimageImageLoader to use of async image downloader with cache support.
NSString *path = [NSString stringWithFormat:#"%#/%#", baseUrl, imageName];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgage = [[UIImage alloc] initWithData:data];
pass this image to your imageview.
As you are loading images from server, you can also use SDWebImage for image caching purpose.
https://github.com/rs/SDWebImage
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];
});
}];
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.
Good afternoon,
I'm trying to display the data in my UITableViewController (CarTableViewController) and at the moment the rows are being populate with the correct info and also the refreshControl is working fine (and very fast, like 1 second) but the first time I entry in my App the data is not displayed (I have to move the screen with my finger and then the data is displayed). (I have to wait like +15 seconds until it appears automatically, but sometimes is not showing).
What can I do in order to display the data automatically and fast?
I tried to move the reloadData into every method and it's always the same and I don't know what else to do...! I will be much appreciated if you can help me with that.
CarTableViewController.m
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
#synthesize likes = _likes;
#synthesize comments = _comments;
#synthesize username = _username;
#synthesize refuser = _refuser;
#synthesize profileImage = _profileImage;
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
[self.tableView reloadData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
self.refreshControl.backgroundColor = [UIColor blackColor];
self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(fetchJson)
forControlEvents:UIControlEventValueChanged];
}
- (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 [_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:#"id"];
cell.likes.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"likes"];
cell.comments.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"comments"];
cell.username.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
cell.refuser.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user_ref"];
cell.modelLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"]];
[cell.carImage setImageWithURL:imageURL
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
options:SDWebImageRefreshCached];
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"image"]];
[cell.profileImage setImageWithURL:imageURL2
placeholderImage:[UIImage imageNamed:#"image"]
options:SDWebImageRefreshCached];
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:
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"date"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"id"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"imagen"],
nil];
}
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://mywebsite.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
#try
{
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
}
#finally
{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}
}
);
}
#end
CarTableViewController.h
#import <UIKit/UIKit.h>
#interface CarTableViewController : UITableViewController
#property (nonatomic, strong) IBOutlet UITableView *tableView;
#property (nonatomic, strong) NSMutableArray *carImages;
#property (nonatomic, strong) NSMutableArray *carMakes;
#property (nonatomic, strong) NSMutableArray *carModels;
#property (nonatomic, strong) NSMutableArray *likes;
#property (nonatomic, strong) NSMutableArray *comments;
#property (nonatomic, strong) NSMutableArray *username;
#property (nonatomic, strong) NSMutableArray *refuser;
#property (nonatomic, strong) NSMutableArray *profileImage;
#property (nonatomic, strong) NSMutableArray *jsonArray;
#end
Thanks in advance.
Your problem is in fetchJson. You're calling reloadData on a background thread, which has unpredictable results. You need to make sure that you call any UI methods on the main thread.
Replace your code with the following:
- (void)fetchJson
{
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://mywebsite.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
error:&error];
for (NSDictionary * jsonObject in _jsonArray)
{
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
});
);
}
Everytime I start scrolling in the tableView the subtitleLabel text keeps overlapping each other in every row. I've tried for the last 4 hours every single search on the Internet for this problem I have clicked and tried.
Here is my ViewController.m:
#interface ANViewController()
{
NSMutableArray *TitleLabel;
NSMutableArray *SubtitleLabel;
NSMutableArray *AvatarImages;
}
#end
#implementation ANViewController
#synthesize thetableview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.thetableview.delegate = self;
self.thetableview.dataSource = self;
TitleLabel = [NSMutableArray array];
SubtitleLabel = [NSMutableArray array];
AvatarImages = [NSMutableArray array];
__block NSArray *posts;
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSError *error;
NSMutableDictionary *allNews = [NSJSONSerialization JSONObjectWithData:allNewsData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
posts = allNews[#"data"];
for (NSDictionary *newsPost in posts) {
[TitleLabel addObject:newsPost[#"title"]];
[SubtitleLabel addObject:newsPost[#"post_message"]];
NSString *avatarUrl = AVATAR_URL;
NSString *avatarExt = #".jpg";
[AvatarImages addObject:[NSString stringWithFormat:#"%#%#%#", avatarUrl, newsPost[#"user_id"], avatarExt]];
}
}
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
long count = TitleLabel.count;
if(count == 0){
count = 1;
}
return count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier;
ANTableViewCell *Cell;
if(TitleLabel.count == 0){
NSLog(#"Did with no news");
CellIdentifier = #"Cell_NoNews";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.noNewsLabel.text = #"No news to display!";
}else{
NSLog(#"Did with news");
CellIdentifier = #"Cell";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.TitleLabel.text = [TitleLabel objectAtIndex:indexPath.row];
Cell.SubtitleLabel.text = [SubtitleLabel objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[AvatarImages objectAtIndex:indexPath.row]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
Cell.AvatarImage.image = img;
}
return Cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
Just change UITableViewCellStyleSubtitle for UITableViewCellStyleDefault, and you need an asynchronous connection instead of a synchronous like you're doing: NSData *allNewsData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:API_URL]]; in your viewDidLoad method that is blocking your main thread.
You can adapt this code to your need, in order to download it on the background:
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});