Loading Json into uitableview - iphone

I am trying to load json into a uitableview. I have worked with json before but never used it with a tableview. I keep getting this error: -[__NSCFNumber count]: unrecognized selector sent to instance. I'm pretty sure it is because in the numberOfRowsInSection method im returning the count of the array. Please let me know how to fix this or if I am missing something and not seeing it.
Here is he code:
.h file
#interface HistoryViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
NSArray *jsonData;
NSMutableData *responseData;
}
.m file
- (void)viewDidLoad
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"Json url"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self ];
[super viewDidLoad];
}
- (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(#"Connection failed: %#", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *dictionary = [responseString JSONValue];
NSArray *response = [dictionary objectForKey:#"name"];
jsonData = [[NSArray alloc] initWithArray:response];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return jsonData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"cell"];
cell.textLabel.text = [jsonData objectAtIndex:indexPath.row];
return cell;
}

All right, I notice that your array is never initialized until the connectionDidFinishLoading method is run. The delegate methods for your data table are likely running before connectionDidFinishLoading, so you should initialize your jsonData array in viewDidLoad instead of connectionDidFinishLoading.
You can keep your connectionDidFinishLoading calls the same, but make sure you call reloadData on your data table at the end of the connectionDidFinishLoading method to fill out your data table with the downloaded data.

Related

parse json for uitableview cell

I have an application using UITableview application. If I click the UITableViewcell that bring JSON data. I created a UIViewController to display the information on the line that was selected in theUITableView. My requirement is if I click the UITableview cell the corresponding PDF File will be displayed in the simulator. I developed the code also. But the pdf file not be displayed on the simulator. I am new to the programming. My doubt is how to download PDF Files using json parser.Plz give me any idea or send me any sample code.Thanks in advance
This is My PDF URLS:
UIViewController Class Reference
QLPreviewController Class Reference
This is my sample code.
JSONPARSERPDFVIEWCONTROLLER .M
-(void)loadData
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#""]];
connect= [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
// delegate methods in json
-(void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response
{
[_data setLength:0];
NSLog(#"didReceiveResponse called");
}
//connection did receive data
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data
{
[_data appendData:data];
}
/ /connection did finish loading
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:_data options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]])
{
//NSArray *jsonArray = (NSArray *)jsonObject;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSArray *array=[[NSArray alloc]init];
array=[jsonDictionary objectForKey:#""];
dataDictionary=[array objectAtIndex:0];
NSLog(#"%#",dataDictionary);
}
[urlsArray addObject:[dataDictionary objectForKey:#"UIViewController"]];
NSLog(#"%#",urlsArray);
//[self dataLoadingFinished:responseString withData:downloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//[connection release];
// = nil;
NSLog(#"didFailWithError called");
}
uitableview.m
- (void)viewDidLoad
{
[super viewDidLoad];
fileNameList = [[NSArray alloc]initWithObjects:#"UIViewController",#"QLPreview class",#"UIDocumentInteractionController", nil];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [fileNameList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [fileNameList objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
jsonparser *jParser=[[jsonparser alloc]init];
jParser.selectedIndex=indexPath.row;
[self.navigationController pushViewController:jParser animated:YES];
}

i want add json framework in ios6 and using that how to fetch data from server? [duplicate]

This question already has answers here:
json parsing+iphone
(4 answers)
Closed 9 years ago.
I have to retrieve data from web-service and store in to table-view.
I have one framework but that cant work for me that is here
HERE PROBLEM IS USING THAT CAN'T ALLOWED TO CREATE CREATE OBJECT OF IT.
Thank you
You don't need to create the object of json.h file. You just need to import json.h file and then use it by [responseString JSONValue].
check this code
#interface videoViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSMutableArray *array2;
}
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray alloc]init];
array2=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://localhost/videosphp/videoname2.php"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webData=[[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Unable to connect internet. Please check your internet connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//use NSDictionary if the data in dictionary
NSArray *allDataArray=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
for (NSDictionary *diction in allDataArray)
{
NSString *videoname=[diction objectForKey:#"videoname"];
[array addObject:videoname];
}
[[self tableview]reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellAccessoryDisclosureIndicator reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[array objectAtIndex:indexPath.row];
return cell;
}

NSURLConnection and SBJSon in AppDelegate

I'm in xCode 4.2 using ARC and Storyboard (iOS 5). I suppose to put Tweets to my TableViewController. As I placed my NSURLConnection, everything goes fine and I have the response already in tweets(NSArray) in the delegate. The problem is it doesn't populate the table view. I am using SBJson for the received data. Am I missing something?
AppDelegate.m
#import "AppDelegate.h"
#import "TwitterViewController.h"
#import "SBJson.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize receivedData;
#synthesize tableViewController;
#synthesize tweets;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
tweets = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://search.twitter.com/search.json?q={username}&rpp=5"]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
if (theConnection) {
receivedData = [NSMutableData data];
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
NSArray *allTweets = [results objectForKey:#"results"];
[tableViewController setTweets:allTweets];
}
#end
This is the delegate methods in my table view controller.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tweets count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"twitter";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *aTweet = [tweets objectAtIndex:[indexPath row]];
NSString *textFrom = [aTweet objectForKey:#"text"];
cell.textLabel.text = textFrom;
return cell;
}
I really need some advice.
Table reload. Gosh! I learned!

iphone load table with wcf

atm i can successfully loading data from a WFC, read the json and put it on the right objects.
But my problem comes when i need to show a table with this data, cuz i don't know where to play the method or when should i call it. Atm looks like the table is created and after that i get the data from the web. Should i reload the table or can i get the info before the class calls cellForRowAtIndexPath: ?
Is there a way to make a connection synchronic and not synchronic? because in this case, if i cant get the list of eventos form wfc its has not point showing a table. So
Thx in advance!
my code:
-(id)init{
//call superclass designated inizialzer
self= [super initWithStyle:UITableViewStyleGrouped];
if(self){
[[self navigationItem] setTitle:#"Eventos"];
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://xxx.xxx.xxx.xxx/..."]];
[[[NSURLConnection alloc] initWithRequest:request delegate:self]autorelease];
}
return self;
}
about connection:
- (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 {
// label.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];
if (luckyNumbers == nil)
// label.text = [NSString stringWithFormat:#"JSON parsing failed: %#", [error localizedDescription]];
[luckyNumbers release];
else {
for (NSDictionary *object in [luckyNumbers objectForKey:#"EResult"]) {
Evento *e=[[Evento alloc] init];
e.nombre= [object objectForKey:#"nombre"];
e._id= (int)[object objectForKey:#"id"];
e.fecha= [object objectForKey:#"fecha"];
[[EventoStore defaultStore]addEvento:e];
[e release];
}
}
}
about the table it self:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[EventoStore defaultStore] allEventos]count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//check for reusable cell first and use it
UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
//if there is no reusable cell, we create one
if(!cell){
cell= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:#"UITableViewCell"]autorelease];
}
Evento *e=[[[EventoStore defaultStore] allEventos] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[e nombre]];
return cell;
}
-(void)tableView:(UITableView *) aTableView didSelectRowAtIndexPath:(NSIndexPath *) indexPax{
LotesViewController *loteViewController= [[[LotesViewController alloc]init]autorelease];
NSArray *eventos=[[EventoStore defaultStore]allEventos];
[loteViewController setEvento: [eventos objectAtIndex:[indexPax row]]];
[[self navigationController]pushViewController:loteViewController animated:YES];
}
you should reload the table after getting the data. you can show the activity indicator on the table till you get the data and once you get the data, you can remove the activity indicator and reload the table. this way you can find the solution to your problem. No need to go for synchronous connection. Just add the activity indicator once the connection is satrted and remove it when data comes.

Is there a way to add Loading View before reload tableview data

I am trying to add Loading data option in viewDidLoad() function before [self.tableview reloaddata]. I am not sure how to add it and is there a way to make the user know that there is data getting loaded.
I am parsing JSON file and the data gets loaded on 3G pretty slow, so its the better way to allow user to know that data is being loaded with loading option. Here is my code:
- (void)viewDidLoad {
[super viewDidLoad];
// Add the view controller's view to the window and display.
responseData = [[NSMutableData data] retain];
self.twitterArray = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://search.twitter.com/search.json?q=mobtuts&rpp=5"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[super viewWillAppear:animated];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *results = [responseString JSONValue];
self.twitterArray = [results objectForKey:#"results"];
[self.tableView reloadData]; // How to add loading view before this statement
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.twitterArray count];
}
I'm not quite sure what you mean by "loading view" but i guess you mean an activity indicator or something else what should be presented while you are loading data.
make an ivar UIActivityIndicatorView *myLoadingView;
Init it in viewDidLoad
myLoadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
myLoadingView.hidesWhenStopped = YES;
[myLoadingView stopAnimating];
[self.view addSubView:myLoadingView];
show the view before you start your connection [myLoadingView startAnimating];
hide it again when the download was finished by stoping it in the delegate method connectionDidFinishLoading: after [self.tableView reloadData]; [myLoadingView stopAnimating];
release it in viewDidUnload [myLoadingView release];
Feel free to ask if you have questions or if i had misunderstood you.