parse json for uitableview cell - iphone

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

Related

Multi call for NSURLConnection with multi UITableView in Same Controller

I have to call two different API in a same view controller and have to show the data on two tableView in same controller, i’m using NSURLConnection for this. but i’m unable to show the result on both of the tableView.
Only urlConnection (for the firstTimeCall) is gave the result . For the secondTimeCall the result is 0.
Can anyone please provide me the samples or able to suggest me the way to do this.
Thanks In Advance.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self firstTimeCall];
[self SecondTimeCall];
}
- (void)firstTimeCall
{
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://xyza.com/key=init"]];
responseData=[[NSMutableData alloc]init];
urlConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
NSLog(#"nsurl FirstTimeCall %#",urlConnection);
}
- (void)SecondTimeCall
{
NSURLRequest *requestTwo=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://abcz.com/key=init"]];
responseDataTwo=[[NSMutableData alloc]init];
urlConnectionTwo=[[NSURLConnection alloc]initWithRequest:requestTwo delegate:self];
NSLog(#"nsurl SecondTimeCall %#",urlConnectionTwo);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
if (connection == urlConnection) {
NSLog(#"Error");
}
else {
NSLog(#"Error");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if (connection == urlConnection) {
[responseData setLength:0];
}
else {
[responseDataTwo setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if (connection == urlConnection) {
[responseData appendData:data];
NSLog(#"%#",responseData);
}
else {
[responseDataTwo appendData:data];
NSLog(#"%#",responseDataTwo);
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == urlConnection) {
NSError *error=nil;
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
self.totalData=[dic objectForKey:#"data"];
NSLog(#"%#",totalData);
NSLog(#"First Time...............%d",totalData.count);
[tableViewOne reloadData];
}
else {
NSError *error=nil;
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
self.totalDataTwo=[dic objectForKey:#"data"];
NSLog(#"%#",totalDataTwo);
NSLog(#"Second Time...............%d",totalDataTwo.count);
[tableViewTwo reloadData];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView==tableViewOne){
NSLog(#"In TableViewOne numOfRow");
return [totalData count];
}else{
NSLog(#"In TableViewTwo numOfRow");
return [totalDataTwo count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"NewCell";
if(tableView==tableViewOne){
NSLog(#"In TableViewOne Cell4Row");
NewCell *cell = (NewCell *)[tableViewOne dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"NewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = #“Testing1;
return cell;
}else{
NSLog(#"TableViewTwo Cell4Row");
NewCell *cell = (NewCell *)[tableViewTwo dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"NewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = #“Testing2”;
return cell;
}
}
I assume that the two NSLog in didReceiveData are fine, but it's just that the log in connectionDidFinishLoading for the second connection is wrong? This would be because the second half of your connectionDidFinishLoading, you're looking at responseData, and I assume you meant to look at responseDataTwo. I'd also suggest you update your NSLog statements to clearly state which is #1 and which is #2 (e.g. in didReceiveData, you're just logging, but you don't know which is which (though by looking at the data, I suspect you can make an intelligent guess.).
Call methods [self firstTimeCall];, and [self SecondTimeCall]; in Synchronous ways. by default this time in ur code you are calling methods in async way.
First call [self firstTimeCall]; method and when you received the response and when you have get call in connectionDidFinishLoading delegate method for firstTimeCall, then start calling SecondTimeCall from here.
Overall first call firstTimeCall adn received its data response from server after completing this call, now call SecondTimeCall.

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

Loading Json into uitableview

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.

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.