- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];(URL1)
self.jsonData = [[NSMutableData alloc]init];(URL2)
self.genderData = [[NSMutableData alloc]init];(URL3)
}
I want to send multiple url at a time what the process to receive response..?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
NSError * error;
id result = (NSMutableArray *)[NSJSONSerialization JSONObjectWithData:self.jsonData options:kNilOptions error:&error];
if (error)
{
NSLog(#"DATA LOAD ERROR");
}
else
{
if([result isKindOfClass:[NSArray class]])
{
titlesArray = result;
}
else
{
titlesDic = result;
}
}
[self genderURLMethod];
}
This is another Delegate Method
When working with NSURLConnection, I tend to go one of two ways.
Always use a different class for each delegate. That way the delegate instance only has to worry about 1 URL.
Use [[connection originalRequest] URL] to distinguish between the different URLs.
Example:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *URLString = [[[[connection originalRequest] URL] absoluteString];
if ([URLString isEqualToString:MY_URL_1]) {
// Handle the response for the first URL.
} else if ([URLString isEqualToString:MY_URL_2]) {
// Handle the response for the second URL/
}
}
Related
I know only getting data for Json.But i need how to getting data for two json url.
i have two Urls and two MutableArrays.Ever time i can handle only one url like this :-
NSURL * url=[NSURL URLWithString:#" url"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
NSLog(#"Connected");
webData=[[NSMutableData alloc]init];
NSLog(#"Connected2");
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return arrayfirst.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return arrayfirst[row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
one.text = arrayfirst[row];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableArray *al=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(#"the array is %#",al);
for(NSArray *arr in al)
{
[arrayfirst addObject:[arr objectAtIndex:1]];
}
}
Please give me any idea about how to handle two Json url. I have two urls BusinessCategory and BusinessLocation I have two MutableArrays arrayfirst and arraysecond. I know about BusinessCategory data pass to arrayfirst. But I don't know how to handle.
You have to create two NSURL connection and handle the response in the delegate.
So, in your header file you can have:
NSURLConnection *conn1;
NSURLConnection *conn2;
NSMutableArray *arrayFirst;
NSMutableArray *arraySecond;
In the implementation file:
//Connection 1
NSURL *url1=[NSURL URLWithString:#"yourjsonurl1"];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url1];
conn1=[[NSURLConnection alloc] initWithRequest:request1 delegate:self];
//Connection 2
NSURL *url2=[NSURL URLWithString:#"yourjsonurl2"];
NSURLRequest *request2 = [NSURLRequest requestWithURL:url2];
conn2=[[NSURLConnection alloc] initWithRequest:request2 delegate:self];
//In your delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (connection==conn1) {
arrayFirst = [[NSMutableData alloc]init];
}
else if (connection==conn2){
arraySecond = [[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (connection==conn1) {
[arrayFirst appendData:data];
}
else if (connection==conn2){
[arraySecond appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (connection==conn1) {
NSLog(#"SOMETHING WENT WRONG WITH URL1");
}
else if (connection==conn2){
NSLog(#"SOMETHING WENT WRONG WITH URL2");
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connection==conn1) {
NSLog(#"DONE WITH URL1");
}
else if (connection==conn2){
NSLog(#"DONE WITH URL2");
}
}
A shorter (and maybe, better) way of doing this is to run it in an asynchronous operation:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *result = [NSData dataWithContentsOfURL:"yourURL"];
id jsonResult;
if ([result length] != 0) { jsonResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"done!");
});
});
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 have set up a simple Objective-C class in my iOS app which has one simple task, to download a JSON file, parse it and then pass back a NSString which contains a variable parsed from the downloaded JSON file.
The problem I have is that I am calling this class from another class and this all works great however I need to pass back the NSString to the class from which I am calling it from.
The problem is that the method passes back the empty NSString BEFORE connectionDidFinishLoading happens.... And so the NSString never gets assigned a string......
I have setup a while loop in my method but it doesn't really work.....
here is my code:
-(NSString *)get_user_icon:(NSString *)YT_ID {
// Set BOOL to 0 for initial setup.
icon_check = 0;
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
dispatch_queue_t downloadQueue = dispatch_queue_create("Icon downloader YouTube", NULL);
dispatch_async(downloadQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLConnection *theConnection_YT = [[NSURLConnection alloc] initWithRequest:theRequest_YT delegate:self];
if (theConnection_YT) {
YT_JSON_FEED = [[NSMutableData alloc] init];
NSLog(#"Respoce happening...");
}
else {
NSLog(#"failed");
}
});
});
while (icon_check == 0) {
NSLog(#"Wait");
}
return icon_url;
}
/// Data loading ///
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[YT_JSON_FEED setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[YT_JSON_FEED appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSString *msg = [NSString stringWithFormat:#"Failed: %#", [error description]];
NSLog(#"%#",msg);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *myError = nil;
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:YT_JSON_FEED options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:#"items"] valueForKey:#"snippet"] valueForKey:#"thumbnails"] valueForKey:#"default"] valueForKey:#"url"];
icon_check = 1;
}
For a synchronous request (blocking until there is something to return), use NSURLConnection's sendSynchronousRequest:returningResponse:error: instead. Like so:
-(NSString *)get_user_icon:(NSString *)YT_ID {
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:theRequest_YT returningResponse:&response error:&error];
//Check response and error for possible errors here.
//If no errors.
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:#"items"] valueForKey:#"snippet"] valueForKey:#"thumbnails"] valueForKey:#"default"] valueForKey:#"url"];
return icon_url;
}
However this is not recommended. You need to change your API to be asynchronous. Either delegate-based, but more preferably, using block-based API.
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.
I want to display a UIProgressView indicating the amount of data received as I request JSON data using touchJSON. I was wondering if there was a way to listen to the size of the data being received.
I request data using the following:
- (NSDictionary *)requestData
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:apiURL]];
NSError *error = nil;
NSDictionary *result = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
if(error != NULL)
NSLog(#"Error: %#", error);
return result;
}
You will have to introduce some more code to include a download status indicator bar. At the moment you download the data with [NSData dataWithConentsOfURL:...]. Instead, you will make a class that uses a NSURLConnection object to download data, accumulate that data in an MSMutableData object, and update your UI accordingly. You should be able to use the ContentLength HTTP header and the - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; updates to determine the status of the download.
Here are some relevant methods:
- (void) startDownload
{
downloadedData = [[NSMutableData alloc] init];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)c didReceiveResponse:(NSURLResponse *)response
{
totalBytes = [response expectedContentLength];
}
// assume you have an NSMutableData instance variable named downloadedData
- (void)connection:(NSURLConnection *)c didReceiveData:(NSData *)data
{
[downloadedData appendData: data];
float proportionSoFar = (float)[downloadedData length] / (float)totalBytes;
// update UI with proportionSoFar
}
- (void)connection:(NSURLConnection *)c didFailWithError:(NSError *)error
{
[connection release];
connection = nil;
// handle failure
}
- (void)connectionDidFinishLoading:(NSURLConnection *)c
{
[connection release];
connection = nil;
// handle data upon success
}
Personally, I think the simplest way to do this is to create a class that implements the above methods to do generic data downloads and interface with that class.
This should be enough to get you what you need.