Linking a twitter search to a custom tableview cell - twitter

okay, here's what I've been scratching my head over for the last few days. I have created a custom cell for my table view. I have created a separate class (customCell.h) for this cell and linked them together in Xcode.
The custom cell has four UIlabels which I have declared in the .h file of the custom cell and linked to the custom cell via storyboard.
I have imported the customCell.h header file into the .h file of my table view controller
I am trying to do a search on twitter, and then populate the table view and custom cell with the details of the various tweets. The issue is I don't know how to link the results of the tweet to the 4 UIlabel outlets in my custom cell.
When I am declaring some of the outlets of the custom cell in my table view implementation file (even though I've imported the .h file of the custom cell) xcode is saying that it does not recognise the name
I've copied the coding below detailing as far as I can get. Any help would be much appreciated. Thanks in advance
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"THIS IS WHERE MY TWITTER SEARCH STRING WILL GO.json"]];
NSError* error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:#"text"];
NSString *name = [[tweet objectForKey:#"user"] objectForKey:#"name"];
NSArray *arrayForCustomcell = [tweet componentsSeparatedByString:#":"];
cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:#"by %#", name];
return cell;
}

You are creating an instance of the UITableViewCell, which is the default class for tableview cells. In your case, you have to create an instance of your customCell class (which extends the UITableViewCell class). You have to do this in you cellForRowAtIndexPath method:
static NSString *CellIdentifier = #"TweetCell";
customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ( cell == nil )
{
cell = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Get the tweet
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
I hope this helped you out!
Steffen.

Related

iOS: How to display parameters in response in tableview?

I am trying to set up a UITableView inside of a UIViewController. I am using storyboard. but when running it on the simulator, the tableview does not display any content. Here is what i tried in Xcode:
1) Drag a table view on UIView.
2) Connect it's outlets (dataSource and delegate).
3) I get response from server like:
[{"email_id":"adas#faga.gs","id":66,"mobile_no":"1236547895","name":"asad","relation":"dsfs"},{"email_id":"raj#ghj.com","id":67,"mobile_no":"5632145412","name":"raj","relation":"xyz"}]
4)Now what i want to do:
In 1st cell i want to display,
name:asad mobile:1236547895 email:adas#faga.gs relation:dsfs
and in 2nd cell,
name:raj mobile:5632145412 email:raj#ghj.com relation:xyz
But i have no idea about how to do this.Please anyone can solve my issue. help will be appreciable.
I do like following way but it's not working.
a) Add a new file to the project, with the Objective-C class template. Name it EmergencyContactCell and make it a subclass of UITableViewCell.
b) then in EmergencyContactCell.h
#interface EmergencyContactCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *name;
#property (nonatomic, weak) IBOutlet UILabel *email;
#property (nonatomic, weak) IBOutlet UILabel *mobile;
#property (nonatomic, weak) IBOutlet UILabel *relation;
c) then MainStoryboard.storyboard, select the prototypecell and in the Identity Inspector change its class to EmergencyContactCell
d) Then connect all outlets
e) I am using AFNetworking to take response from server, when i got response, after that i do like following way:
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
menuItems = [ResponseArray mutableCopy];
[yourTableviewname reloadData];
}
f) and for display it on cell,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [menuItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EmergencyContactCell";
//static NSString *simpleTableIdentifier = #"cell";
EmergencyContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
// NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
// cell.textLabel.text = [NSString stringWithFormat:#"Name:%#, Mobile:%#, Email:%#, Relation:%#",content[#"name"],content[#"mobile_no"],content[#"email_id"],content[#"relation"]];
//
return cell;
}
I'm not getting what to do at last??
Step-1
No need of this
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSDictionary *temp in ResponseArray) {
[finalArray addObject:temp[#"name"]];
}
NSLog(#"%#",finalArray);
if(finalArray != nil && finalArray.count > 0){
menuItems=[NSArray arrayWithArray:finalArray];
NSLog(#"menu items: %#",menuItems);
}
else{
NSLog(#"zero values from server");
}
Simply Do like
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
menuItems = [ResponseArray mutableCopy];
[yourTableviewname reloadData];
}
Step-2
for your answer continution
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"Name:%#, Mobile:%#, Email:%#, Relation:%#",content[#"name"],content[#"mobile_no"],content[#"email_id"],content[#"relation"]];
return cell;
}
Updated Answer
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EmergencyContactCell";
EmergencyContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
cell.name.text = [NSString StringWithFormat:#"Name:%#",content[#"name"]];
cell.email.text = [NSString StringWithFormat:#"email:%#",content[#"email"]];
cell.mobile.text = [NSString StringWithFormat:#"mobile:%#",content[#"mobile"]];
cell.relation.text = [NSString StringWithFormat:#"relation:%#",content[#"relation"]];
return cell;
}
You need to do 2 things
After getting response set that into one NSArray. Declare NSArray
global one. And your code should be like
NSArray *arrayPersonalInfo = responseObject; // responseObject is response
got from server. Then call [tableView reloadData];
Now update your table view methods to
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return arrayPersonalInfo.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSDictionary *dictionaryMenu = [arrayPersonalInfo objectAtIndex:indexPath.row]; // It will save dictionary object of index
cell.textLabel.text = [NSString stringWithFormat:#"Name:%# Mobile:%# Email:%# Relation:%#",[dictionaryMenu valueForKey:#"name"],[dictionaryMenu valueForKey:#"mobile_no"],[dictionaryMenu valueForKey:#"email_id"],[dictionaryMenu valueForKey:#"relation"]];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
}
If needed add other table view methods like
heightForRowAtIndexPath and numberOfSections
If you prefer using storyboard, you can actually add a label into a prototype cell, make sure you set the prototype's cellIdentifier correctly to use it in codes. Then set a unique tag to your label. From your codes you can call viewWithTag from your cell's contentView to get the label and edit it's text property.

Objective C read csv and populate in tableview

Hi guys I am new to Objective C. I want to make an app where it can read a csv file locally and display the data in a specific column in the tableview.
1)Read csv locally
2)Display csv data (let's say fifth column "ItemName") in the tableview
Thanks for any advice.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *strPath = [[NSBundle mainBundle] pathForResource:#"issues" ofType:#"csv"];
NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
if (!strFile) {
NSLog(#"Error reading file.");
}
issues = [[NSArray alloc] init];
issues = [strFile componentsSeparatedByString:#","];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return[issues count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [issues objectAtIndex:indexPath.row];
return cell;
}
The way you do the parsing is only making columns of the whole file. First you need to separate by line-breaks (probably '\n'), then you can separate each line by ',' and each time take the 5th element and add it to an NSMutableArray (issues).
[strFile componentsSeparatedByString:#","] is not really CSV-parsing, there are more complex libraries available for that on cocoapods. If you need error-handling, etc. you better go with a library.

Parsing JSON in UITableviewcell

I am new to iOS. i have to parse following JSON and display it to UITableViewCell. individual array is appearing in cell when i parse and append country item only. but all arrays for ex. rank ,country , population , flag are not appearing in cell.
how to add all rank , country , population , flag in array and put all them in cell. i have taken all them into string and then into array. and whole array i appended to main array.
following is JSON -
http://www.androidbegin.com/tutorial/jsonparsetutorial.txt
code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSArray *arrayWorldPopulation = [allDataDictionary objectForKey:#"worldpopulation"];
for (NSDictionary *diction in arrayWorldPopulation)
{
NSString *country = [diction objectForKey:#"country"];
NSString *population = [diction objectForKey:#"population"];
NSString *flag = [diction objectForKey:#"flag"];
NSArray *temparray = [[NSArray alloc] initWithObjects:rank,country,population,flag, nil];
[array addObject:temparray];
}
[maintableView reloadData];
}
At a minimum, you need to implement tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath in your view controller. This tells the table how many rows to expect and what each row in the table looks like. The simple code below assumes you have an array of strings and are just displaying one string per cell and should get you started. Your specific situation sounds like it may require a custom cell design. This tutorial describes how to do this in a storyboard with a custom cell class.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count]; //tell the UITableView how many are items are in the array
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
//stuff to make sure iOS is reusing cells rather than creating new ones
static NSString *MyIdentifier = #"MyReuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
NSString *itemFromArray = [array objectAtIndex:indexPath.row]; //get the item for that cell
cell.textLabel.text = itemFromArray; set the cell to display the text
return cell;
}

Objective-C : Table cell just returns last information of matching data

I'm trying to insert data into the rows I've created, I will get all info in my Log but it only shows the last info in all of my rows. Could anyone suggest a way to avoid this error?
Please offer me some advice thanks!
You are never re-populating the cells, actually. You are creating the initial visible cells, and just reusing them with the same content.. please look below:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static NSString *CellIdentifier = #"TestCell";
TestCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// HERE YOU ONLY WANT TO INSTANTIATE THE CELL
NSArray *topObjects = [[NSBundle mainBundle] loadNibNamed:#"TestCell" owner:nil options:nil];
for (id currentObject in topObjects)
{
if([currentObject isKindOfClass:[TestCell class]])
{
cell = (TestCell *) currentObject;
break;
}
}
}
// HERE YOU WOULD ACTUALLY POPULATE THE CELL WITH DATA
NSArray *array = [server get_texts:10 offset:0 sort_by:0 search_for:#""];
NSMutableString *s = [[NSMutableString alloc] init];
for (testMetaData *m in array){
[s appendFormat:#"%# %# \n", m.title,m.note];
cell.title.text = m.title;
NSLog(#" title %# ", m.title);
}
return cell;
}
Some info about UITableView:
So, a properly setup tableView only allocates and uses a limited number of UITableViewCells. After allocating, say 5 cells (this number is determined by "How many cells can you see at any given time?"), it will take an already created cell that has been scrolled out of the visible area, and gives it back to you in that method you are using, so you can re-populate it. So, cell variable will not be nil at that time, and your server code never gets called.
I think it has to do with your for loop.
NSMutableString *s = [[NSMutableString alloc] init];
for (testMetaData *m in array){
[s appendFormat:#"%# %# \n", m.title,m.note];
cell.title.text = m.title;
NSLog(#" title %# ", m.title);
}
Your cell.title.text = m.titlewill get the last m.title info at the end of the for loop.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
//Load Cell for reuse
static NSString *CellIdentifier = #"TestCell";
TestCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell =[ [[NSBundle mainBundle] loadNibNamed:#"TestCell" owner:nil options:nil] lastObject];
}
//appending text and config cell
NSArray *array = [server get_texts:10 offset:0 sort_by:0 search_for:#""];
NSString *t = [array objectAtIndex:indexPath.row];
//Config cell - Not sure what you want. Maybe 10 different rows
cell.title.text = t;
return cell;
}

How to insert UIImage to UITableViewCell

I've got a problem with UIImage in the tableviewcell that are in storyboard.
When i scroll cell in the tableview it request the data from the server everytime so cell is very slow.
I've watched this video
but it does not work on storyboard, because storyboard donesn't have UITableViewCell NIB file (its integrate to the storyboard)
What I do in my project
I create object and link to my outlet property
I use json to get data from internet.
I display it on the tableview.
You can download my entire project file here. This is code in the UITableview.m cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MyCell";
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
NSDictionary *entry = [ _entries objectAtIndex:indexPath.row];
cell.boomTitle.text = [entry objectForKey:#"body"];
NSString *imageURL=[NSString stringWithFormat:#"http://kelnakub.co.cc/upload/%i.jpg",[[entry objectForKey:#"IdEntry"] intValue]];
for(NSDictionary *dic in _entries)
{
NewsFeed *myNewsFeed = [[NewsFeed alloc]init];
myNewsFeed.thumNail = [dic objectForKey:#"IdEntry"];
}
NSURL *url = [NSURL URLWithString:imageURL];
NSData *imageData = [NSData dataWithContentsOfURL:url];
cell.boomImage.image = [UIImage imageWithData:imageData];
cell.boomDate.text = [entry objectForKey:#"dateCreated"];
return cell;
}
You can use UITableViewCell in a NIB file using storyboard. Just use prototype cells and, instead of designing the cell on the Storyboard, create a new NIB and design the UITableViewCell on it (Storyboard's UITableView remains empty of cells).
Then, in the code, you can load the cell using something like: UITableViewCell * MyCustomCell = [[[NSBundle mainBundle] loadNibNamed:#"MyCustomCell" owner:self options:nil] objectAtIndex:1];

Resources