I have a problem with my tableview. I'm trying to make a program that downloads job details from my database and lists them. The tableview is still blank, the view is connected to the specific controller and I have checked that the JSON feed and cell identifier are OK. My cell rows are also strange, the row lines continue over the right edge though I have aligned the tableview object correctly. I had similar problems with my previous project but didn't know what was wrong.
Here is a part of the code (Source from: http://codewithchris.com/iphone-app-connect-to-mysql-database/)
JobViewer.m
#interface JobViewer()
{
NSMutableData *_downloadedData;
}
#end
#implementation JobViewer
- (void)downloadItems
{
// Getting json file
NSURL *jsonFileURL = [NSURL URLWithString:#"here is my correct URL"];
//Making request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileURL];
//Creating NSURLConnection with the request
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//Initialize data
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//Append the data that was downloaded
[_downloadedData appendData:data];
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection
{
//Creating array for the information
NSMutableArray *_jobs = [[NSMutableArray alloc] init];
// Parsing the JSON file
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
//Looping through JSON objects and storing them into array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonObject = jsonArray[i];
//Creating a new object and getting data from JSON element
Job *newJob = [[Job alloc] init];
newJob.jobid = jsonObject[#"Job_id"];
newJob.companyid = jsonObject[#"Company_id"];
newJob.customer = jsonObject[#"Customer"];
newJob.phone = jsonObject[#"Phone"];
newJob.email = jsonObject[#"Email"];
newJob.address = jsonObject[#"Address"];
newJob.city = jsonObject[#"City"];
newJob.header = jsonObject[#"Header"];
newJob.notes = jsonObject[#"Notes"];
newJob.date = jsonObject[#"Date"];
newJob.driver = jsonObject[#"Driver"];
//Added question to array
[_jobs addObject:newJob];
}
// Passing the done data and passing items back
if (self.delegate)
{
[self.delegate itemsDownloaded:_jobs];
}
}
#end
MainViewController.m
#interface MainViewController ()
{
JobViewer *_jobViewer;
NSArray *_listObjects;
}
#end
#implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.mainList.delegate = self;
self.mainList.dataSource = self;
_listObjects = [[NSArray alloc] init];
_jobViewer = [[JobViewer alloc] init];
_jobViewer.delegate = self;
[_jobViewer downloadItems];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)itemsDownloaded:(NSArray *)items
{
_listObjects = items;
[self.mainList reloadData];
}
#pragma mark Table View Delegate Methods
// You may remove this method
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _listObjects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = #"InfoCell";
UITableViewCell *newCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Job *item = _listObjects[indexPath.row];
newCell.textLabel.text = item.address;
//[newCell setBackgroundColor:[UIColor blackColor]];
return newCell;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
You likely need to add "InfoCell" as the reuse identifier in your Storyboard.
Probably your tableView doesn't recognise the cell so you should add the cell at tableView in the storyboard and it is called "InfoCell"
If you don't want to add cell into tableView in the storyboard and you have a xib with your cell. you can call in your viewController this method:
[tableView registerNib:[UINib nibWithNibName:#"IndoCell" bundle:nil] forCellReuseIdentifier:#"IndoCell"];
that if your nib is called "IndoCell.xib"
Related
I am trying to to pretty standard operation, which is basically, getting all records form my local SQLITE database, then getting additional data form web, merge this data (which is NSMutableArray) and display it in table view. In viewDidLoad, array has all required elements, but in numberOfRowsInSection: it equals to nil. Because of this, I cannot display items in tableview. So where could it get set to nil? Thank you for any help.
Code for InboxViewControler.m
//
// ArticleViewController.m
// ReadLater
//
// Created by Ibragim Gapuraev on 09/06/2014.
// Copyright (c) 2014 Sermilion. All rights reserved.
//
#import "InboxViewController.h"
#import "LoginViewController.h"
#import "SHCTableViewCell.h"
#interface InboxViewController ()
#end
#implementation InboxViewController
#synthesize db, articles, response, jsonData;
- (NSMutableArray* ) articles
{
if (!articles) {
articles = [[NSMutableArray alloc] initWithCapacity:20];
}
return articles;
}
- (Database* ) db
{
if (!db) {
db = [[Database alloc] init];
}
return db;
}
//---------------------------------Getting data from web-------------------------------------------//
/**
The method will connect to a given url and send date of article that has been added at last.
Then, connectionDidFinishLoading will receive json array of all articles, that have been added to server database after that time
**/
#pragma mark Connection to server
- (void) makeConnetion:(id)data
{
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost/nextril/index.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//send id of article that was added last, to server,
//which will return json arrya of all articles with id greater then the one sent
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
if (connection) {
NSLog(#"viewWillAppear: Connecting to server to get data...");
}else{
NSLog(#"viewWillAppear: Error while connecting...");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
response = [[NSData alloc] initWithData:data];
}
//Check if data been received
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if(sizeof(response)>0){
//NSLog(#"Got response from server %#", response);
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:response //1
options:kNilOptions
error:&error];
self.jsonData = [[NSMutableArray alloc] initWithArray:json];
int count = 0;
[self.db openDatabase];
BOOL added = false;
BOOL addedToUser = false;
NSLog(#"jsonData %d", jsonData.count);
for (int i=0; i<self.jsonData.count; i++) {
NSDictionary *item = [self.jsonData objectAtIndex:i];
NSString* content = [item objectForKey:#"content"];
NSString* author = [item objectForKey:#"author"];
NSString* date = [item objectForKey:#"date"];
NSString* url = [item objectForKey:#"url"];
NSString* tags = [item objectForKey:#"tags"];
NSInteger archived = [[item objectForKey:#"archived"]integerValue];
NSString* title = [item objectForKey:#"title"];
//NSLog(#"",);
Article* article = [[Article alloc]initWithId:0 content:content author:author date:date url:url tags:tags arhived:archived title:title];
added = [self.db addArticleToArticleDB:article];
if (added == true) {
NSInteger last_id = [self.db getLastArticleID];
article.article_id = last_id;
[self.articles addObject:article];
addedToUser = [self.db addArticleToUserArticleDB:article];
}
count++;
}
if (added == true && addedToUser == true) {
NSLog(#"connectionDidFinishLoading: Articles has been imported. Size: %d %lu", jsonData.count, (unsigned long)jsonData.count);
}else{
NSLog(#"connectionDidFinishLoading: Failed to import article.");
}
NSArray *importedArticles = [self.db importAllArticlesForUser:16 archived:0];
[self.articles addObjectsFromArray:importedArticles];
[self.db closeDatabase];
}else{
NSLog(#"connectionDidFinishLoading: Did not get resopnse from server: %#", response);
}
connection = nil;
}
//----------------------------------------------------------------------------------------------------
#pragma mark TODO: work out why data from server loads only after second login
#pragma mark view
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.db openDatabase];
NSString* date_added = [self.db getLastArticleDate];
[self makeConnetion:(id)date_added];
NSLog(#"viewWillAppear: self.articles: %d", self.articles.count);
[self.db closeDatabase];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.separatorColor = [UIColor clearColor];
self.tableView.backgroundColor = [UIColor blackColor];
[self.tableView registerClass:[SHCTableViewCell class] forCellReuseIdentifier:#"Content"];
}
#pragma mark - Table view data source
- (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.
NSLog(#"numberOfRowsInSection: self.articles: %d", self.articles.count);
return self.articles.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Content";
SHCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.backgroundColor = [UIColor clearColor];
NSMutableArray* safeArticles = self.articles;
// Configure the cell...
Article* article = [safeArticles objectAtIndex:indexPath.row];
NSString *listingKey = article.title;
NSString *listingValues = article.url;
cell.textLabel.text = listingKey;
cell.detailTextLabel.text = listingValues ;
cell.delegate = self;
cell.todoItem = article;
return cell;
}
#pragma mark cell atributes
-(UIColor*)colorForIndex:(NSInteger) index {
NSUInteger itemCount = self.articles.count - 1;
float val = ((float)index / (float)itemCount) * 0.6;
return [UIColor colorWithRed: 1.0 green:val blue: 0.0 alpha:1.0];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 70.0f;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [self colorForIndex:indexPath.row];
}
#pragma mark TODO delete from server database
//method to delete an article form view and to call method to delete from database, as well as form server database
-(void)deleteArticle:(Article*)articleToDelete {
. . .
}
#pragma mark TODO delete from server database
//method to delete an article form view and to call method to delete from database, as well as form server database
-(void)archiveArticle:(Article*)articleToArchive {
. . .
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
A tableView calls the datasource methods to populate itself just after viewDidLoad. If, at that point, the data source (which is usually an Array) is empty, nothing will appear in the tableView. That is why one has to call reloadData after the data source is brought into existence. This is especially needed in cases the data source is being fetched asyncronously.
According to Apple's documentation about reloadData:
Call this method to reload all the data that is used to construct the
table, including cells, section headers and footers, index arrays, and
so on. For efficiency, the table view redisplays only those rows that
are visible. It adjusts offsets if the table shrinks as a result of
the reload. The table view's delegate or data source calls this
method when it wants the table view to completely reload its data. It
should not be called in the methods that insert or delete rows,
especially within an animation block implemented with calls to
beginUpdates and endUpdates
Took advice of #akashg and added [self.tableView reloadData]; after fetching data. And it worked. Though, I don't know the mechanism of why this happened. At least it works ) Anyone welcome to add their explanation. Thank you.
C/xcode geeks!
I have been struggling with this error for hours now, and I don't seem to find the solution, although it seems as many people have had the exact same problem.
See code:
//
// ListViewController.m
// Puns
//
// Created by Amit Bijlani on 12/13/11.
// Copyright (c) 2011 Treehouse Island Inc. All rights reserved.
//
#import "ListViewController.h"
#import "BlogPost.h"
//#import "Pun.h"
#import "PunsTableViewCell.h"
#import "DetailViewController.h"
#implementation ListViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - Segue
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSLog(#"0");
if ( [[segue identifier] isEqualToString:#"ShowMenu"] ){
NSLog(#"1");
DetailViewController *dvc = (DetailViewController *)[segue destinationViewController];
dvc.menu = [self.blogPosts objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// GET WEB DATA SOURCE (JSON)
// The url
NSURL *blogURL = [NSURL URLWithString:#"http://constantsolutions.dk/json.html"];
// The data
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
// Error variable
NSError *error = nil;
// jsonData to serialization
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
// Get array 'posts'
self.blogPosts = [NSMutableArray array];
NSArray *blogPostsArray = [dataDictionary objectForKey:#"posts"];
for (NSDictionary *bpDictionary in blogPostsArray) {
// Get title
// Will only retrieve data, if TITLE exists
BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:#"title"]];
// Get the content
blogPost.content = [bpDictionary objectForKey:#"content"];
// Get thumbnail
blogPost.thumbnail = [bpDictionary objectForKey:#"thumbnail"];
// Get date
blogPost.date = [bpDictionary objectForKey:#"date"];
// Get price
blogPost.price = [bpDictionary objectForKey:#"price"];
// Add the object to blogPosts array
[self.blogPosts addObject:blogPost];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (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.blogPosts count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"PunTableViewCell";
PunsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[PunsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
BlogPost *blogPost = [self.blogPosts objectAtIndex:indexPath.row];
cell.menuTitle.text = blogPost.title;
cell.menuContent.text = blogPost.content;
if([blogPost.price length] == 0) {
[cell.menuPrice setHidden:YES];
} else {
cell.menuPrice.text = blogPost.price;
}
return cell;
}
#end
As you can see, I have implented NSLog() inside the prepareForSegue, but it is not triggered.
Do you guys have any idea what I am doing wrong? I am pretty new to this, so I still haven't found out this whole iPhone development thing. So bare over with me if the solution is simple :o).
Thanks in advance!
You have a name for the segue, so does that mean you created it by dragging from a button or table view cell to the other view controller and then selected it and named it in xcode? if you are programmatically changing the view it wont be called but you can manually call a method before swapping views to prepare
I had a similar issue in going about sharing information in ios between views where the answer may be helpful.
In particular from the answer on that post where he says:
"in your .m file you would trigger you segue - maybe on a button or some action. sounds like you already have this:"
[self performSegueWithIdentifier:#"viewB" sender:self];
--
Swapping your segue name in of course.
I'm trying to load Lazy Tableview in a custom cell in storyboard, but the table view just looks blank:
This is the source code:
LazyLoadTable.m
#import "CellData.h"
#import "LazyLoadTableView.h"
#import "CustomCell.h"
#import "ParseOperation.h"
#import "ImageDownloader.h"
#define kCustomRowHeight 157
#define kCustomRowCount 1
static NSString *const xmlDataUrl =
#"http://itunes.apple.com/us/rss/topfreeapplications/limit=300/xml";
#interface LazyLoadTableView ()
#end
#implementation LazyLoadTableView
#synthesize tableElements;
#synthesize queue;
#synthesize connection;
#synthesize xmlData;
#synthesize tView;
#synthesize imageDownloadsInProgress;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.tableElements=[[NSMutableArray alloc] init];
self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title=#"Menu";
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:xmlDataUrl]];
self.connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
// Test the validity of the connection object.
NSAssert(self.connection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count = [tableElements count];
// ff there's no data yet, return enough rows to fill the screen
if (count == 0)
{
return kCustomRowCount;
}
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// customize the appearance of table view cells
static NSString *placeholderCellIdentifier = #"PlaceholderCell";
// add a placeholder cell while waiting on table data
int nodeCount = [self.tableElements count];
if (nodeCount == 0 && indexPath.row == 0)
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:placeholderCellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:placeholderCellIdentifier];
cell.detailTextLabel.textAlignment = NSTextAlignmentCenter ;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.detailTextLabel.text = #"Loading…";
return cell;
}
static NSString *CustomCellIdentifier = #"CustomCellIdentifier";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id oneObject in nib) if ([oneObject isKindOfClass:[CustomCell class]])
cell = (CustomCell *) [nib objectAtIndex:0];
}
// Leave cells empty if there's no data yet
if (nodeCount > 0)
{
// Set up the cell...
CellData *cellData = (self.tableElements)[indexPath.row];
cell.name.text = cellData.name;
// Only load cached images; defer new downloads until scrolling ends
if (!cellData.icon)
{
if (self.tView.dragging == NO && self.tView.decelerating == NO)
{
[self startIconDownload:cellData forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
cell.itemImage.image = [UIImage imageNamed:#"Placeholder.png"];
}
else
{
cell.itemImage.image = cellData.icon;
}
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return kCustomRowHeight;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.xmlData = [NSMutableData data]; // start off with new data
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.xmlData appendData:data]; // append incoming data
}
#pragma mark -
#pragma mark NSURLConnection delegate methods
- (void)handleError:(NSError *)error
{
NSString *errorMessage = [error localizedDescription];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Cannot Show Data"
message:errorMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
// if we can identify the error, we can present a more precise message to the user.
NSDictionary *userInfo = #{NSLocalizedDescriptionKey: #"No Connection Error"};
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
code:kCFURLErrorNotConnectedToInternet
userInfo:userInfo];
[self handleError:noConnectionError];
}
else
{
// otherwise handle the error generically
[self handleError:error];
}
self.connection = nil; // release our connection
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.connection = nil; // release our connection
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// create the queue to run our ParseOperation
self.queue = [[NSOperationQueue alloc] init];
ParseOperation *operation = [[ParseOperation alloc] initWithData:self.xmlData delegate:self];
[queue addOperation:operation]; // this will start the "ParseOperation"
self.xmlData = nil;
}
- (void)didFinishParsing:(NSArray *)cellDataList
{
[self performSelectorOnMainThread:#selector(handleLoadedApps:) withObject:cellDataList waitUntilDone:NO];
self.queue = nil; // we are finished with the queue and our ParseOperation
}
- (void)parseErrorOccurred:(NSError *)error
{
[self performSelectorOnMainThread:#selector(handleError:) withObject:error waitUntilDone:NO];
}
- (void)handleLoadedApps:(NSArray *)loadedCellData
{
[self.tableElements addObjectsFromArray:loadedCellData];
// tell our table view to reload its data, now that parsing has completed
[self.tView reloadData];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)startIconDownload:(CellData *)cellData forIndexPath:(NSIndexPath *)indexPath
{
ImageDownloader *imageDownloader = imageDownloadsInProgress[indexPath];
if (imageDownloader == nil)
{
imageDownloader = [[ImageDownloader alloc] init];
imageDownloader.cellData = cellData;
imageDownloader.indexPathInTableView = indexPath;
imageDownloader.delegate = self;
imageDownloadsInProgress[indexPath] = imageDownloader;
[imageDownloader startDownload];
}
}
// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
if ([self.tableElements count] > 0)
{
NSArray *visiblePaths = [self.tView indexPathsForVisibleRows];
for (NSIndexPath *indexPath in visiblePaths)
{
CellData *cellData = (self.tableElements)[indexPath.row];
if (!cellData.icon) // avoid the app icon download if the app already has an icon
{
[self startIconDownload:cellData forIndexPath:indexPath];
}
}
}
}
// called by our ImageDownloader when an icon is ready to be displayed
- (void)imageDidLoad:(NSIndexPath *)indexPath
{
ImageDownloader *imageDownloader = imageDownloadsInProgress[indexPath];
if (imageDownloader != nil)
{
CustomCell *cell = (CustomCell *)[self.tView cellForRowAtIndexPath:imageDownloader.indexPathInTableView];
// Display the newly loaded image
cell.itemImage.image = imageDownloader.cellData.icon;
}
}
#pragma mark -
#pragma mark Deferred image loading (UIScrollViewDelegate)
// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate)
{
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize itemImage;
#synthesize name;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
Didn't read through all that code but it looks like you are trying to lazy load an image with some text. I highly recommend using SDWebImage for the lazy loading. It's simple and very straightforward to set up.
While I was surfing over the Internet I've found a lot of examples how to load array in the TableViewController, but none of them helped me!
Couldn't you help me to find what is wrong in my code ?
Thank you in advance!!!
#import "Images.h"
#import "AFNetworking.h"
#import "HTMLparser.h"
#interface Images ()
#end
#implementation Images
#synthesize data;
#synthesize textFromVC1;
#synthesize tableView;
#synthesize so2;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.data = [[NSMutableArray alloc]init];
NSError *error = nil;
NSString *so = [#"http://" stringByAppendingString: self.textFromVC1];
NSURL *url = [[NSURL alloc]initWithString:so];
NSString *str=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
HTMLParser *parser = [[HTMLParser alloc] initWithString:str error:&error];
if (error) {
NSLog(#"Error: %#", error);
[parser release];
parser = nil;
return;
}
HTMLNode * body = [parser body];
NSArray *inputs = [body findChildTags:#"img"];
for (HTMLNode *input in inputs) {
NSString *links = [input getAttributeNamed:#"src"];
NSString *so1 = [so stringByAppendingString: #"/"];
so2 = [so1 stringByAppendingString: links];
[self.data addObject:so2];
NSLog(#"%#", data);
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
}];
[operation start];
}
[self.tableView reloadData];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidUnload
{
[self setTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"LinkID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.textLabel.text = [self.data objectAtIndex:indexPath.row];
[self.tableView reloadData];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
- (void)dealloc {
[tableView release];
[super dealloc];
}
#end
well 1) numberOfSections is 0. to see something it should be one IIRC
think thats it but havent double checked
Assuming your data array is built up correctly, your mistake in is your numberOfSections methods. Currently, it returns 0, which tells the UITableView that there are currently no sections to be displayed… ever.
You can either return 1; there or remove the entire method altogether. The default implementation, which you inherit from UITableViewController, also returns 1 by default.
My advice would be to remove the method, as that keeps your own code cleaner. You can always implement it in a later stage, when you might actually need it.
Ok, here is my code:
(appname)AppDelegate.h:
#import <UIKit/UIKit.h>
#class TwitterViewContoller;
#interface <appname>AppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UITabBarController *rootController;
TwitterViewContoller *viewController;
NSMutableData *responseData;
NSMutableArray *tweets;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UITabBarController *rootController;
#property (nonatomic, retain) IBOutlet TwitterViewContoller *viewController;
#property (nonatomic, retain) NSMutableArray *tweets;
#end
(appname)AppDelegate.m:
#import "<appname>AppDelegate.h"
#import "TwitterViewContoller.h"
#import "SBJson.h"
#implementation <appname>AppDelegate
#synthesize window = _window;
#synthesize rootController;
#synthesize viewController;
#synthesize tweets;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
responseData = [[NSMutableData data] retain];
tweets = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=USER_NAME_ID"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
//[window addSubview:rootController.view];
//[window makeKeyAndVisible];
return YES;
}
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
//NSDictionary *results = [responseString JSONValue]; <---This...
//NSArray *allTweets = [results objectForKey:#"results"]; <--- and this was original code but it caused an exception,
NSArray *allTweets = [responseString JSONValue]; //<-- So I used this instead.
NSLog(#"THE ARRAY = %#", allTweets); //<-- THE ARRAY IS SHOWING FINE IN THE OUTPUT LOG
[viewController setTweets:allTweets];
[self.window addSubview:rootController.view];
[self.window makeKeyAndVisible];
}
- (void)dealloc {
[_window release];
[rootController release];
[viewController release];
[super dealloc];
}
#end
TwitterViewContoller.h: (yes, I know I spelt it wrong - lol)
#import <UIKit/UIKit.h>
#import "SBJson.h"
#interface TwitterViewContoller : UIViewController {
IBOutlet UILabel *label;
NSArray *tweets;
IBOutlet UITableView *tview;
}
#property(nonatomic, retain) IBOutlet UILabel *label;
#property(nonatomic, retain) NSArray *tweets;
#end
TwitterViewContoller.m:
#import "TwitterViewContoller.h"
#import "Tweet.h"
#implementation TwitterViewContoller
#synthesize label;
#synthesize tweets;
#pragma mark -
#pragma mark Table view data source
- (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 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 80;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSLog(#"THE ARRAY = %#", tweets); //<--ARRAY IS NULL <-- <-- <--
NSDictionary *aTweet = [tweets objectAtIndex:[indexPath row]];
cell.textLabel.text = [aTweet objectForKey:#"text"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:12];
cell.textLabel.minimumFontSize = 10;
cell.textLabel.numberOfLines = 4;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.text = [aTweet objectForKey:#"screen_name"];
NSURL *url = [NSURL URLWithString:[aTweet objectForKey:#"profile_image_url"]];
NSData *data = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData:data];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
tweets = [[NSArray alloc]init];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void) dealloc {
[tweets release];
[super dealloc];
}
#end
The problem is that my UITableView is showing up but none of my tweets are. I have noticed that the "tweets" array in TwitterViewContoller (I know I spelt it wrong) is empty (the null problem is fixed) but "allTweets" in my AppDelegate isn't empty. Any ideas?
Test to ensure that in your app delegate, the viewController property is not nil. If you have miswired it in IB (I don't see any instantiation of it in your app delegate), it will silently fail when you call setTweets.
Also, if your view controller is visible and you re-set the tweets property, the table view won't update itself. Instead of synthesizing your tweets property, write your own getter and setter, like so (you could also use KVO for this purpose if you like)
-(NSMutableArray*)tweets {
return [[tweets retain] autorelease];
}
-(void)setTweets:(NSMutableArray*)newTweets {
if(newTweets != tweets) {
[newTweets retain];
[tweets release];
tweets = newTweets;
[tView reloadData];
}
}
As an aside, you should have -tableView:numberOfRowsInSection: return [tweets count] rather than a fixed number, and it isn't necessary to implement -tableView:heightForRowAtIndexPath: if your rows are all the same height -- you can just set the rowHeight property in IB or in code on the table view.
Update
If your view controller property isn't getting populated, it might be easiest to just load and add it manually in -application:didFinishLaunchingWithOptions -- I think your current approach of delaying the display of any interface until the web request finishes is conceptually problematic. What happens if the network isn't available? Here's some code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// ... omitting the first few lines
// let's make sure that we have the tab bar controller, at least
NSAssert(nil != self.rootViewController, #"tab bar controller not hooked up!");
self.viewController = [[[TwitterViewContoller alloc] initWithNibName:#"TwitterViewContoller" andBundle:nil] autorelease];
self.rootViewController.viewControllers = [NSArray arrayWithObject:self.viewController];
// this is now the Right Way to set the root view for your app, in iOS 4.0 and later
self.window.rootViewController = self.rootViewController;
[self.window makeKeyAndVisible];
}
There are a lot of ways that you can confuse yourself when you're starting a new project. I like to customize all of my views to have hideous background colors at first so I always know if they're on screen or not -- using ugly colors helps ensure that I don't forget to change them later.