ReloadData not working in my TableViewController - ios

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];
});
);
}

Related

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];
});
}];

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

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.

JSON Image View Showing Object at same Index

I have a UIImageView in side a UIView, which displays an object #"photos" in a JSON Array as such: http://topmobiletrends.com/wp-content/uploads/2013/10/screen568x568-14.jpeg
My NSLog tells me that all the objects have been parsed correctly. But the UIImageViews inside UIViews show the same image, I believe it is the first object [0]. I need to have the views show each image for all of the objects for the #"photos" key.
Here is my code for my ViewController.m:
. . .
#interface ViewController ()
{
NSInteger index;
}
//#property (nonatomic, weak)NSURL *imageURL;
#end
#implementation ViewController
#synthesize menuButton;
#synthesize myImage;
#synthesize priceLabel;
-(void)viewDidLoad{
[super viewDidLoad];
NSURL *bburl = [NSURL URLWithString:#"http://www.suchandsuch.com/api/sites"];
NSData *jsonData = [NSData dataWithContentsOfURL:bburl];
NSURLSession *session = [NSURLSession sharedSession];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:bburl];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:bburl completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error){
NSLog(#"%#", response);
NSData *data = [[NSData alloc]initWithContentsOfURL:location];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSString *imageURLString = [[[dataDictionary objectForKey:#"sites"] objectAtIndex:index] objectForKey:#"photo"];
NSURL *imageURL = [NSURL URLWithString:[imageURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"sites : %#", imageURLString);
NSArray *sitesArray = [dataDictionary objectForKey:#"sites"];
NSMutableArray *photos = [[NSMutableArray alloc]initWithArray:sitesArray];
for (NSDictionary *item in sitesArray) {
MyObject *current = [MyObject alloc];
current.name = [item objectForKey:#"name"];
current.url = [item objectForKey:#"url"];
current.price = [item objectForKey:#"price"];
current.photo = [item objectForKey:#"photo"];
[photos addObject:current];
NSLog(#"%#", current.photo);
}
for (MyObject *photo in photos)
{
dispatch_async(dispatch_get_main_queue(),^{
UIView *dView = [[UIView alloc]initWithFrame:CGRectMake(30,30,258,229)];
UIImage *image = [UIImage imageWithData:data];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
imageView.frame = CGRectMake(30, 30, 258, 229);
//Get image from url
[self.imageView setImageWithURL:imageURL];
//[self.myImage addSubview:imageView];
[dView addSubview:imageView];
[self.view addSubview:dView];
// priceLabel.text = [[[dataDictionary objectForKey:#"sites"] objectAtIndex:index] objectForKey:#"price"];
});
}
}];
[task resume];
}
There are a few issues with the code.
You are adding both NSURL and name string to the photos array but when reading you are expecting all of them to be photos.
I would recommend create a data structure called Photo which contains
#interface PhotoClass :NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSURL *url;
#property (nonatomic, strong) NSString *price
#property (nonatomic, strong) NSString *photo;
#end
That way you can do the following when parsing your data.
PhotoClass *current = [PhotoClass alloc];
current.name = [item objectForKey:#"name"];
current.url = [item objectForKey:#"url"];
current.price = [item objectForKey:#"price"];
current.photo = [item objectForKey:#"photo"];
// Add to array
[photos addObject:current];
And then when you are ready to display use the url from each PhotoClass object.
The next issue in your code is with the image view setup. First of all You will need to create as many ImageViews. each one needs to be offset to the other can be visible behind that image. Plus the image view seems to be getting set in many diff ways. Is that just a typo? :
for (PhotoClass *photo in photos)
{
dispatch_async(dispatch_get_main_queue(),^{
UIView *dView = [[UIView alloc]initWithFrame:CGRectMake(50,50,258,229)];
// The frame of each of the frames needs to be offset a little ..
// so you need to figure out how to calculate that for each image.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:photo.url]];
[dView addSubview:imageView];
[self.view addSubview:dView];
....
}];
}
At the end of the loop you should have as many image views in view as objects in photos.
Disclaimer - code not compiled and typed directly into stackoverflow browser

Cell text overlapping when scrolling in UITableView Xcode iOS

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];
});
});

Images on UITableView NOT WORKING

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;
}

Resources