I have data returned from a service that is rendered to my UITableView several times. I moved placed the code that populates my table in the connectionDidFinishLoading delegate. Is this the correct placement of that code?
I have a NSMutableData* receivedData; at the top of my .m file and I have implemented the correct delegates and overridden the correct methods.
I just want to know what I am missing here or what I can do to only see the data from my JSON once in the table view.
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
NSLog(#"%#",response);}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"Succeeded! Received %d bytes of data",[data length]);
receivedData = [[NSMutableData alloc] init];
[receivedData appendData:data];}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error = nil;
// Get the JSON data from the website
id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
if ([result isKindOfClass:[NSArray class]]) {
for (NSArray *item in result) {
NSArray *category = [item valueForKey:#"CategoryName"];
[dataArray addObject:category];
}
}
else {
NSDictionary *jsonDictionary = (NSDictionary *)result;
for(NSDictionary *item in jsonDictionary)
NSLog(#"Item: %#", item);
}
[self.tableView reloadData];
NSLog(#"Finished");}
I believe you have a line with an error
receivedData = [[NSMutableData alloc] init];
Every time you receive the data you are initializing your object again.
I do recommend this page http://nsscreencast.com/episodes/6-afnetworking for your JSON part.
Related
i have a PHP webservices. My requirement is using PHP web services to display json data in UIView one by one.
The Json data is :
"id\":\"6\",\"title\":null,\"description\":null,\"year\":\"2012\",\"date\":null}","{\"id\":\"4\",\"title\":\"
correct in the year 2013\",\"description\":\"<\/font> Financial
system in America for this year is not indicated progress this year
too. More problems will creep up. \r\n<\/font> Aggressive stage
of Telangaana agitation- formation of seperate Telangaana state-
bifurcation of state - sure indications are \r\n\r\npredicted.
\r\n*<\/font> The Gujarath CM - Sri Narendra Modi - Bright future
is indicated. \r\n*<\/font> Still danger is indicated for
Indoneshia and Sumitra Islands.
i want to display these data in UIView.Before display each line of data displaying * symbol.How to retrieve and how to display in UIViewcontroller.Help me any body.Thanks in advance.
I am writing like this.but i got exception.
-(void)loadData
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults valueForKey:#"id"];
[defaults valueForKey:#"title"];
[defaults valueForKey:#"description"];
[defaults synchronize];
NSURL *url=[NSURL URLWithString:#"http://www.predictions.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
urlConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData=[[NSMutableData alloc]init];
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(connection==urlConnection)
{
strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResponse);
NSError *error;
jsonDict=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonDict);
NSArray *arrResults=[jsonDict valueForKey:#"id"];
NSLog(#"%#",arrResults);
arrString=[NSMutableArray array];
for(NSDictionary *dictRes in arrResults)
{
constants *con=[[constants alloc]init];
con.titl=[dictRes valueForKey:#"title"];
// con.desc=[dictRes valueForKey:#"description"];
[arrString addObject:con];
}
[View1 reloadData];
}
}
You can use NSJSONSerialization class for parsing JSON objects.
Hope this helps.
You should use this framework: https://github.com/stig/json-framework and SBJsonParser class to parse the JSON script. The below code will help you parse json response:
SBJSON *parser = [[SBJSON alloc] init] ;
NSDictionary *dic = (NSDictionary *)[parser objectWithString:respString error:nil];
This code will convert your response string in the respString variable into an NSDictionary, and now you can extract each object by calling:
NSString* response = [dic objectForKey:#"response"];
I am calling the webservice string using the NSURLConnection , I am getting wrong data in response in success method of NSURLConnection , But if i load same URL in browser i am getting correct response. I am using below code .
NSData *mydata=[srtRes dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *returnArry =[[NSMutableArray alloc]init];
returnArry = [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingMutableContainers error:&e];
How to resolve this issue. Kindly give suggestion and answers.
Try this one :
// In .h class
#property (nonatomic,retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *temp_arr;
// In .m class
#synthesize responseData;
#synthesize temp_arr;
- (void)viewDidLoad
{
NSString *urlString=#"http://your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
}
Delegate Method of JSON Parsing :
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray * returnArry = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
NSDictionary *nameDic = nil;
for (int i = 0 ; i < [returnArry count]; i++)
{
nameDic = [returnArry objectAtIndex:i];
[self.temp_arr addObject:[nameDic objectForKey:#"name"]]; // According your key you have to save data in temp_arr.
}
}
Please follow this , if any doubt let me know :)
I want to update my json file in ios app which is offline compiled in the app. When the app is refreshed the file should get updated from the server : localhost:8888/ios/ios_app/Service/data.json
Please help...
Thank you in advance
I use SOAP when i need get value that can be serialized to a string type. But if all what you need is json file, look at NSURLConnection class.
- (void)downloadJSONFromURL {
NSURLRequest *request = ....
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
// ...
}
NSData *urlData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[urlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
if (jsonParsingError) {
DLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
DLog(#"OBJECT: %#", [object class]);
}
}
I am new in the ios field, Now i am trying to implement MKMapView Based iPhone Application. From the Google Map Web web service i Fetch the Data in JSON Output Format.
- (void)update {
self.responseData=[NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=Ernakulam&destination=Kanyakumari&mode=driving&sensor=false"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
self.responseData =nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"connection established");
[connection release];
NSString *responseString=[[NSString alloc]initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData=nil;
NSLog(#" OUTPUT JSON DATA^^^^^^^^^^^^^^^^%#",responseString);
}
I got the out put has in the JSON Format. Now i want to draw route between this two location. sow how can i separate all the latitude and Longitude points from the JSON out put Data.
Check out this code. I am using JSONkit for parsing
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"connection established");
[connection release];
NSString *responseString=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *data1 = [responseData objectFromJSONData];
NSMutableArray *ad = [data1 objectForKey:#"routes"];
NSMutableArray *data2 = [[ad objectAtIndex:0] objectForKey:#"legs"];
NSMutableArray *data3 = [[data2 objectAtIndex:0] objectForKey:#"steps"];
// NSLog(#"Data3 %#", data3);
for(int i = 0; i<data3.count;i++){
NSLog(#"Start %#", [[data3 objectAtIndex:i] objectForKey:#"start_location"]);
NSLog(#"End %#", [[data3 objectAtIndex:i] objectForKey:#"end_location"]);
}
}
I am using SBJson to parse json data.
In general, call [responseString JSONValue] to get parsed data.
You can google it for detail reference.
Im using json to load a table in my app from a twitter web service,
it works fine when using the search function,
http://search.twitter.com/search.json?q=mobtuts&rpp=5
the type of json response for the first one is: tenga: {"completed_in" = "0.076"; ...
but when I use the statuses function,
[NSURL URLWithString:#"http://twitter.com/statuses/user_timeline.json?id=hypercomputing"]];
the type of json response for the second one is: tenga: (
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Thu Aug 04 23:26:05 +0000 2011";...
the result from json is different, so my app doesnt see the second call as a dictionary once imported from json, it sees it as a string, [because of the "(" ??]
here the code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
responseData = [[NSMutableData data] retain];
tweets = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
// [NSURL URLWithString:#"http://twitter.com/statuses/user_timeline.json?id=hypercomputing"]];
[NSURL URLWithString:#"http://search.twitter.com/search.json?q=mobtuts&rpp=5"]];// hypercomputing
//[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json?id=hypercomputing"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
return YES;
}
#pragma mark NSURLConnection delegate methods
- (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 {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"string: %#",responseString);
NSDictionary *results = [responseString JSONValue];
NSLog(#"tenga: %#",results);
//NSLog(#"tenga: %#",[results objectForKey:#"("] );
//NSArray * keys = [results allKeys]; //ensa
//NSLog(#"keys: %#",keys); //ensayo
NSArray *allTweets = [results objectForKey:#"results"];
//NSArray *allTweets = [results objectForKey:#"user"];
NSLog(#"user is: %#",allTweets);
//[viewController setTweets:allTweets];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
so how can I make sure to receive a dictionary from the json call?,
thanks a lot!
Instead of expecting a dictionary every time, considering testing the class of the incoming JSON object and writing code that handles each case.
Or, more to your point, write an intermediary web service to massage the JSON into something your app can recognize.
Since you're working with defined APIs offered by Twitter, you'll have to read up on the documentation to know what to expect and adjust your implementation accordingly. This isn't a case where you can change the data to meet your needs, you have to change the handling of the data.