I am using HTMLParser by Ben Reeves. It works great but the only problem is that I couldn't put the output in UITableView. Anyone can tell me what's wrong with this code? ...................................................................................
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSError *error = nil;
NSURL *url=[[NSURL alloc] initWithString:#"http://website.com/"];
NSString *strin=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
HTMLParser *parser = [[HTMLParser alloc] initWithString:strin error:&error];
if (error) {
NSLog(#"Error: %#", error);
return;
}
HTMLNode *bodyNode = [parser body];
NSArray *divNodes = [bodyNode findChildTags:#"div"];
for (HTMLNode *inputNode in divNodes) {
if ([[inputNode getAttributeNamed:#"class"] isEqualToString:#"views-field-title"]) {
NSLog(#"%#", [inputNode allContents]);
listData = [[NSArray alloc] initWithObjects:[inputNode allContents], nil];
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
#end
You're reinitializing your array every time you find a new element. I think you need to move
listData = [[NSArray alloc] initWithObjects:[inputNode allContents], nil];
outside of your loop and change it to
listData = [[NSMutableArray alloc] init];
listData should be an NSMutableArray so you can add data to it. You'll need to change this in your variable definition too.
Then inside your loop, use [listData addObject:[inputNode allContents]];
Related
i'm using json rss feed parsing in my rss app, i have table view loading titles , thumbnails and sending links of titles to a web view each in it's own nsmutable array, however , i'm adding a pull to refresh in my app , i followed alot of tutorials , i added the code, when i pull , i get the spinning wheel , and loads and stops, but my new feed isn't loaded, how do i make sure the parsing method gets recalled , bnot just refreshen table happens , below is my code :
#import "APPMasterViewController.h"
#import "APPDetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#interface APPMasterViewController () {
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSMutableString *thumbnail;
NSString *element;
UIRefreshControl *refreshControl;
}
#end
#implementation APPMasterViewController
- (void)awakeFromNib
{
[super awakeFromNib];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
[[UINavigationBar appearance] setBarTintColor:UIColorFromRGB(0xcf1717)];
[[UINavigationBar appearance] setBarStyle:(UIBarStyleBlackTranslucent)];
}
- (void)viewDidLoad {
[super viewDidLoad];
feeds = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://icuore.ly/category/ipad/feed/"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(refresh) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
}
- (void)refresh {
[self.tableView reloadData];
[refreshControl endRefreshing];
NSLog(#"fetching data from the server");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return feeds.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey: #"title"];
//cell image set
NSString *imageStr = [[feeds objectAtIndex:indexPath.row] objectForKey: #"thumbnail"];
NSString *trimmedString = [imageStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *string1=[trimmedString stringByReplacingOccurrencesOfString:#"/n" withString:#""];
NSURL *url = [NSURL URLWithString:string1];
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *newImage = [UIImage imageWithData:data];
//cell.imageView.image = newImage;
CALayer * roudning = [cell.imageView layer];
[roudning setMasksToBounds:YES];
[roudning setCornerRadius:30.0];
[cell.imageView setImageWithURL:url
placeholderImage:[UIImage imageNamed:#"icuore_logo.jpg"]];
return cell;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
element = elementName;
if ([element isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
title = [[NSMutableString alloc] init];
link = [[NSMutableString alloc] init];
thumbnail = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"item"]) {
[item setObject:title forKey:#"title"];
[item setObject:link forKey:#"link"];
[item setObject:thumbnail forKey:#"thumbnail"];
[feeds addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([element isEqualToString:#"title"]) {
[title appendString:string];
} else if ([element isEqualToString:#"link"]) {
[link appendString:string];
} else if ([element isEqualToString:#"thumbnail"]) {
[thumbnail appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[self.tableView reloadData];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
//
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *string = [feeds[indexPath.row] objectForKey: #"link"];
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *string1=[trimmedString stringByReplacingOccurrencesOfString:#"/n" withString:#""];
NSLog(#"you clicked %#", [feeds[indexPath.row] objectForKey: #"link"]);
[[segue destinationViewController] setUrl:string1];
}
//my modified passing
}
#end
i found the answer , i had to empty the table view , and recall the nsurl , reload data and end refreshing , it works perfectly now
here is the code everyone:
- (void)refresh {
[feeds removeAllObjects];
NSURL *url = [NSURL URLWithString:#"http://icuore.ly/category/ipad/feed/"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[self.tableView reloadData];
[refreshControl endRefreshing];
NSLog(#"fetching data from the server");
}
I developed an App in xcode 4.2 that reads data from a phpMyAdmin database and loads it to a tableview. Now if I do the same inxcode 4.3, it doesn't work anymore. I am looking for a solution since days now, but can't find any and I have no idea why it doesn't work (my database and php script works fine).
FirstViewController.h:
NSMutableArray *myArray;
FirstViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
myArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions
error:&error];
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [myArray count];
}
- (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];
}
NSDictionary *info = [myArray objectAtIndex:indexPath.row];
cell.textLabel.text = [info objectForKey:#"name"];
cell.detailTextLabel.text = [info objectForKey:#"Message"];
return cell;
}
I'm very new to this, so pardon my ignorance.
I have the following method that I've pieced together and I get no errors when it's running, and I verified that I'm getting data from the web service. What I do notice is that when I put a breakpoint on the numberOfRowsInSection method it returns 0 both times. I assume that means I'm not loading my array correctly.
Declare my messages property in the header
#property (nonatomic, strong) NSArray *messages;
Synthesize that property in the m file
#synthesize messages;
This is the method that loads the data and is supposed to reload the table
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response
{
if ([response isOK])
{
// Success! Let's take a look at the data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData: [[response bodyAsString] dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:nil];
if([[result objectForKey:#"result"] isEqualToString:#"success"])
{
NSArray *message_array = [result objectForKey:#"messages"];
for(NSUInteger i = 0; i < [message_array count]; i++)
{
EHRXMessage *m = [[EHRXMessage alloc] init];
NSDictionary *message = [message_array objectAtIndex: i];
m.subject = [message objectForKey:#"Title"];
m.callback_name = [message objectForKey:#"CallbackName"];
[self.messages setValue:m forKey:[NSNumber numberWithInt:i]];
}
[self.tableView reloadData];
}
else
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Inbox Error!"
message:#"Error loading messages"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
And here is the method where I tell it how to load the cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MessageCell"];
EHRXMessage *message = [self.messages objectAtIndex:indexPath.row];
cell.textLabel.text = message.callback_name;
cell.detailTextLabel.text = message.subject;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.messages count];
}
And here's a snippet of what the json looks like
{"result":"success","count":"0", "messages":[{"SenderID":"6fcb7c19-b21f-4640-a237-0e7ac5ca0ce8","Title":"General","Message":"","CallbackName":"Claudia","CallbackNumber":"1295","EncounterID":null,"AdmissionID":"d7387243-3e8a-42e4-8a85-fdd3428dae68","DateSent":"3/9/2012 12:52 PM"}]}
- (void)viewDidLoad
{
[super viewDidLoad];
self.loaded = FALSE;
NSURL *URL = [NSURL URLWithString:#"http://46.136.168.166:8000/test.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
// creating loading indicator
self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
if(connection){
self.recievedData = [NSMutableData data];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
NSDictionary *item = [self.dataBase objectAtIndex:[indexPath section]];
NSArray *item_d = [item allKeys];
[[cell textLabel] setText:[item objectForKey:[item_d objectAtIndex:[indexPath row]]]];
return cell;
}
- (void)fetchedData:(NSMutableData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
[self setDataBase:[json objectForKey:#"json-data-header"]];
[self.table reloadData];
}
Do you have numberOfRowsInSection?
EDIT
Be sure to initialize the data source (self.messages)
i have just install the xcode 4.2.1 with ios5 and i try to use json.
this my code
-(void)start
{
responseData = [[NSMutableData data]retain];
membreArray = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http:******.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(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
{
NSLog(#"error %#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
jsonArray = [responseString JSONValue];
NSLog(#"array %#",jsonArray);
}
in my NSLog(#"array %#",jsonArray); i can see all records,everything is ok. But in my tableview nothing at the screen.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [jsonArray count];
}
// 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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
NSDictionary *dico = [self.jsonArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dico objectForKey:#"name"];
return cell;
}
this code work on xcode 3 but not in xcode 4.
somes helps please.
After you finish loading the data, you need to tell your tableview to reload. I'm not seeing that in your code. Try something like this:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
jsonArray = [responseString JSONValue];
NSLog(#"array %#",jsonArray);
/* This tells your tableView to reload */
[tableView reloadData];
}
Also, make sure your TableView is connected in the designer via an IBOutlet. Otherwise your reloadData command will fall on deaf ears.
I have this url: http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false
And this code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSMutableDictionary *theDictionary = [responseString JSONValue];
NSLog(#"%#", theDictionary);
[responseString release];
if (theDictionary != nil)
{
NSArray *routesArray = [theDictionary objectForKey:#"routes"];
NSDictionary *firstRoute = [routesArray objectAtIndex:0];
NSArray *legsArray = [firstRoute objectForKey:#"legs"];
NSDictionary *firstLeg = [legsArray objectAtIndex:0];
steps = [firstLeg objectForKey:#"steps"];
}
[tableView reloadData];
}
I want to display every single #"html_instructions" on a uitableview.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.steps count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cachedCell"];
if (cell == nil)
cell = [[[UITableViewCell alloc]
initWithFrame:CGRectZero reuseIdentifier:#"cachedCell"] autorelease];
return cell;
}
What's missing in my code??? Should be some little detail... any help would be GREAT!
I would do it like this:
Create url request with your url
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false"]];
then create NSData structure, that holds response to the request and I converted it to string
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
After that, you load JSON into Dictionary, then to move one level down, pass it to another dictionary (result 1)
NSError *error=nil;
result = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
result1 = [result objectForKey:#"routes"];
result2 = [result1 objectForKey:#"legs"];
Then move it into NSMutableArray
jsonMutArray= [result2 objectForKey:#"steps"];
From there, you just put label into your custom cell attach it as a IBOutlet, synthetize and do in cellForRowAtIndexPath method
cell.yourLabel.text = [jsonMutArray objectForKey:#"html_instructions"];
However, keep in mind, that I'm just begginer, so this might not be the most effective way of doing it :) Good Luck!
Don't you need to be doing something like this in your CellForRowAtIndexPath ?
NSString *cellValue = **WHATEVER VALUE YOU WANT TO PUT IN**;
cell.textLabel.text = cellValue;
return cell;
I don't see you adding your data to the cell.