json ios5 nothing at the screen - json

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.

Related

Which is the best method to fetch data from JSON url?

I have a application in which when we login a new view controller will be loaded which is a table view and data need to be fetched from server by Json call.Which is the best method to use in this situation.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://YourURL.com/FakeURL/PARAMETERS"]];
[request setHTTPMethod:#"GET"];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
or
-(void)update{
NSString *urlAsString = [NSString stringWithFormat:#"http://YourURL.com/FakeURL/PARAMETERS"];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
self.responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:
url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
NSString *errorDisplay = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
NSLog(#"%#",errorDisplay);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
}
Or i should use Asynchronous Method
-(void)updateCheckList{
self.checkListresponseData = [NSMutableData data] ;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8080/outing-service-web/checkList/all"]];//asynchronous call
checkListConn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[self.checkListresponseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.checkListresponseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
NSString *errorDisplay = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
NSLog(#"%#",errorDisplay);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Cannot connect to server" delegate:nil cancelButtonTitle:nil otherButtonTitles: #"Retry",#"Close",nil];
[alertView show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == checkListConn) {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.checkListresponseData length]);
// convert to JSON
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.checkListresponseData options:NSJSONReadingMutableLeaves error:&myError];
}
}
If you do it asynchronously, then the process will be done in the background.
In short, synchronous requests block the execution of code which creates "freezing" on the screen and an unresponsive user experience.
Check the following URL, it might get you more clear idea.
Synchronous and Asynchronous Requests

pull to refresh uitableview json parsing data

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

loading phpMyAdmin-database to UITableView

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

Parsed results in UITableView

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

IOS Loading data into a table from a web service

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)