I am trying to get json response from a web-service api. I want to extract product data from the json. I also want to implement this using AFNetworking and i also trying to get response using NSURLSession and its completely working.
viewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tblTableView;
- (IBAction)btnClickedPostData:(id)sender;
#end
viewController.m
#import "ViewController.h"
#import "AFNetworking.h"
#import "ResponseTableViewCell.h"
#interface ViewController ()
{
NSMutableDictionary *dictArray;
NSMutableArray *dataArray;
}
#end
#implementation ViewController
static NSString *CellIdentifier = #"cell";
- (void)viewDidLoad {
[super viewDidLoad];
[self.tblTableView registerNib:[UINib nibWithNibName:#"ResponseTableViewCell" bundle:nil] forCellReuseIdentifier:#"ResponseTableViewCell"];
[self connectionString];
}
-(void)connectionString
{
//NSURL *URL = [NSURL URLWithString:#"Your URL"];
NSURLSession *session = [NSURLSession sharedSession]; // its working
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"YOUR URL"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonResponse);
dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
self.tblTableView.dataSource = self;
self.tblTableView.delegate = self;
[self.tblTableView reloadData];
NSLog(#"JSON: %#", dataArray);
}];
[dataTask resume];
// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // its working
// [manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//
// NSMutableDictionary *jsonResponse = (NSMutableDictionary *)responseObject;
// dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
//
// self.tblTableView.dataSource = self;
// self.tblTableView.delegate = self;
//
// [self.tblTableView reloadData];
//
// NSLog(#"TableView: %#", _tblTableView);
//
//
// NSLog(#"JSON: %#", dataArray);
// } failure:^(NSURLSessionTask *operation, NSError *error) {
// NSLog(#"Error: %#", error);
// }];
}
#pragma marrk
#pragma marrk - TableView DataSource and Deleget
#pragma marrk
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];// its not working
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ResponseTableViewCell *cell = (ResponseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"ResponseTableViewCell"];
dictArray = [dataArray objectAtIndex:indexPath.row];
//cell.lblCatID.text = [dictArray objrct:#""];
cell.lblCatID.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryId"]];
cell.lblEventName.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryName"]];
cell.lblCreateDate.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"CreatedDate"]];
cell.layoutMargins = UIEdgeInsetsZero;
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:#selector(setSeparatorInset:)])
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:#selector(setLayoutMargins:)])
{
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)])
{
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 144.0;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnClickedPostData:(id)sender {
NSString *tokenString = #"65d188d3f0ab52487001c331584ac819";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
[defaultConfigObject setHTTPAdditionalHeaders:#{ #"token" : tokenString}];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:#"YOUR URL"];
NSString *paramString = #"lang=en&title=&start=&end=";
NSData *httpBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:60.0];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[httpBody length]];
[urlRequest addValue: #"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setHTTPMethod:#"POST"];
//[urlRequest setAllHTTPHeaderFields:paramString];
[urlRequest setAllHTTPHeaderFields:#{ #"token" : tokenString}];
[urlRequest setHTTPBody:httpBody];
//[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSError *parseError = nil;
NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
if (!error && respHttp.statusCode == 200) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSMutableArray *arrArray = [responseDictionary objectForKey:#"newslist"];
NSString *title = [NSString stringWithFormat:#"%#", [arrArray valueForKey:#"title"]];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Details" message:title delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:#"Cancel", nil];
[alert show];
NSLog(#"%#", arrArray);
}else{
NSLog(#"%#", error);
}
}];
[dataTask resume];
}
#end
//CustomeTableviewCell With XIB
**ResponseTableViewCell.h**
#import <UIKit/UIKit.h>
#interface ResponseTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *lblCatID;
#property (weak, nonatomic) IBOutlet UILabel *lblEventName;
#property (weak, nonatomic) IBOutlet UILabel *lblCreateDate;
#end
**ResponseTableViewCell.m**
#import "ResponseTableViewCell.h"
#implementation ResponseTableViewCell
#synthesize lblCatID,lblEventName,lblCreateDate;
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
// and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzA[Click to show JSON demo Hear][1]
//add custom table view cell with custom table cell and add label to display information. i used pod to setup AFNetworking.
and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzAClick to show JSON demo Hear
Can anyone suggest a way to do this.me how the things will be done.
You Can use also use sqlite for the data.
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");
}
xcode newbie trying to get UISearchBar functionality working.
I am using storyboards and my tableview controller shows a list of events (title, location & start date)in the cells from the array json. When the table firsts loads all of my results are displayed ok. When I click put some text into the search bar (text that exists in the title) nothing is shown in the view controller (I.e. it filters all of the events out). Hopefully this makes a bit more sense.
My header file is
#import <UIKit/UIKit.h>
#define kGETUrl #"http://www.max-momentus.com/fetchevents.php5"
#interface MMAllEventsViewController : UITableViewController <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *json;
NSMutableArray *jsonFiltered;
BOOL isFiltered;
}
#property (weak, nonatomic) IBOutlet UISearchBar *eventSearchBar;
#property (strong, nonatomic) IBOutlet UITableView *eventTableView;
#property (strong, nonatomic) NSString *categorySelected;
#property (strong, nonatomic) NSString *displayDate;
#end
My implementation file is
#import "MMAllEventsViewController.h"
#import "MMEventDetailViewController.h"
#import "MMCategoryViewController.h"
#import "MMEventCell.h"
#interface MMAllEventsViewController ()
#end
#implementation MMAllEventsViewController
#synthesize categorySelected, displayDate;
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"EventDetailSegue"]) {
// Segue code
}
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
-(void) getData:(NSData *) data {
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self.tableView reloadData];
}
-(void) start {
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.eventSearchBar.delegate = self;
self.eventTableView.delegate = self;
self.eventTableView.dataSource = self;
[self start];
}
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length == 0) {
isFiltered = NO;
}
else {
isFiltered = YES;
for (int i = 0; i < [json count]; i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [json objectAtIndex:i];
NSString *name = [NSString stringWithFormat:#"%#", [temp valueForKey:#"Title"]];
NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
[jsonFiltered addObject:name];
}
i++;
}
}
[self.eventTableView reloadData];
}
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.eventTableView resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered) {
return [jsonFiltered count];
}
return [json count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EventCell";
MMEventCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[MMEventCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (!isFiltered) {
NSDictionary *info = [json objectAtIndex:indexPath.row];
cell.eventTitleLabel.text = [info objectForKey:#"Title"];
cell.locationLabel.text = [info objectForKey:#"Location"];
NSString *startDate = [info objectForKey:#"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *sdate = [dateFormatter dateFromString:startDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedStartDate = [dateFormatter stringFromDate:sdate];
NSString *endDate = [info objectForKey:#"EndDate"];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *edate = [dateFormatter dateFromString:endDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedEndDate = [dateFormatter stringFromDate:edate];
if([sdate isEqualToDate:edate]) {
displayDate = convertedStartDate;
} else {
displayDate = [convertedStartDate stringByAppendingString:#" to "];
displayDate = [displayDate stringByAppendingString:convertedEndDate];
}
cell.datesLabel.text = displayDate;
}
else {
NSDictionary *info = [jsonFiltered objectAtIndex:indexPath.row];
cell.eventTitleLabel.text = [info objectForKey:#"Title"];
cell.locationLabel.text = [info objectForKey:#"Location"];
NSString *startDate = [info objectForKey:#"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *sdate = [dateFormatter dateFromString:startDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedStartDate = [dateFormatter stringFromDate:sdate];
NSString *endDate = [info objectForKey:#"EndDate"];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *edate = [dateFormatter dateFromString:endDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedEndDate = [dateFormatter stringFromDate:edate];
if([sdate isEqualToDate:edate]) {
displayDate = convertedStartDate;
} else {
displayDate = [convertedStartDate stringByAppendingString:#" to "];
displayDate = [displayDate stringByAppendingString:convertedEndDate];
}
cell.datesLabel.text = displayDate;
}
return cell;
}
#end
Have you made sure you have the delegates: in your view controllers .h file? Also, make sure you've selected the "UISearchBar and UISearchDisplay Controller" as your search bar object from the storyboard (assuming you're using storyboards). Make sure you've linked your SearchBar to have your view controller be its delegate, and it's connected to an IBOutlet object in your code (again, assuming your using storyboards:
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
Finally, make that you have declared a UISearchDisplayController variable, linked it to your UITableView and then make sure when loading the results from a search, to check in your
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
and
- (NSInteger)numberOfRowsInTableView:(UITableView *)tableView
if:
if(tableView == searchDisplay):
{
...load results.
}
else
{
...load normal view
}
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 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]];
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)