I'm trying to parse a XML File. It worked very well - until today...
Here's how I start to parse the XML:
NSString *link = [[NSString alloc] init];
link = #"link_to_xml_file";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
And here's how I'm using the received data:
- (void)connection:(NSURLConnection *)theConnection
didReceiveData:(NSData *)incrementalData
{
if (data == nil)
data = [[NSMutableData alloc] init];
[data appendData:incrementalData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",actual]];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] error:&parseError];
if (parseError != nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[parseError localizedDescription] delegate:nil cancelButtonTitle:#"Zurück" otherButtonTitles:nil];
[alert show];
[alert release];
} //shows an alertview with NSXMLParserErrorDomain error 5
NSLog(#"String: %#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); //returns null
NSLog(#"Dictionary: %#",xmlDictionary); //returns null
NSMutableDictionary *tempDictForAddDate = [[NSMutableDictionary alloc] initWithDictionary:xmlDictionary];
NSDateFormatter *originalDate = [[NSDateFormatter alloc] init];
[originalDate setDateFormat:#"dd.MM.yyyy"];
NSString *today = [originalDate stringFromDate:[NSDate date]];
[tempDictForAddDate setObject:today forKey:#"updated"];
[tempDictForAddDate writeToFile:filePath atomically:YES];
self.contentList = [[tempDictForAddDate objectForKey:#"xmlObject"] objectForKey:#"event"];
[self sortContent];
}
The XML-File works in my browser. And every tag is closed. There aren't any errors but I never get the data of the file.
I hope someone can help.
mavrick3.
You are (wisely) using asynchronous url connection, but this means your didReceiveData delegate will be called multiple times as the data comes in, so it won't be complete at the point you are parsing it.
You probably want to move the parsing into the following delegate method.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
See Apple's Documentation here
EDIT:
Always a good idea to formally validate your XML - I tend to use the w3c tools http://www.w3schools.com/xml/xml_validator.asp
Also, when things that used to work stop working, I always ask myself what has changed? Is the file different? Is it larger? Are you sure it is present on the server and your browser isn't using a cached version?
Related
I am trying to load web content asynchronously. I have a large amount of web calls in my viewdidappear method and my app is very unresponsive. I understand the concepts of synchronous and asynchronous loading of content, but don't know how to tell if this is being done asynchronously. The code below is simply embedded in my viewdidappear method, and I assume it is loading synchronously. How would I edit this to make it load asynchronously? Thank you all!
NSString *strURLtwo = [NSString stringWithFormat:#"http://website.com/json.php?
id=%#&lat1=%#&lon1=%#",id, lat, lon];
NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]];
NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0
error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
You can use NSURLConnectionDelegate:
// Your public fetch method
-(void)fetchData
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://website.com/json.php?id=%#&lat1=%#&lon1=%#",id, lat, lon]];
// Put that URL into an NSURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
Implement the delegate methods:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[jsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// All data is downloaded. Do your stuff with the data
NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
jsonData = nil;
connection = nil;
}
// Show AlertView if error
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
connection = nil;
jsonData = nil;
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
For asynchronous web content loading, I recommend you to use AFNetworking . It'll solve lots of your major headache of networking in future. How to do:
1) subclass AFHTTPCLient, for example:
//WebClientHelper.h
#import "AFHTTPClient.h"
#interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
#end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = #"http://whateverBaseURL.com/";
#implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
#end
2) Request asynchronously your web content, put this code in any relevant part
NSString *testNewsURL = #"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Response: %#", szResponse );
//PUT your code here
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Operation Error: %#", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];
Hi every One I am new to iPhone. I am retrieving data from remote server with using nsurlconnection and json parser..I am downloaded only one file from the server and i stored in documents path. But in my server url number of files are there like (images,audios,video,text files). How to download at a time when app lunch and save it in document directory. And also i want the same file name in documents as the file name in the server.
I have tried these way .
ViewController
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
NSMutableData *responseData;
NSArray *filesCount;
}
#property(nonatomic,retain)NSArray *filesCount;
#property(nonatomic,retain) NSMutableData *responseData;
#end
.m viewController
#import "ViewController.h"
#import "JSON/JSON.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize filesCount,responseData;
- (void)viewDidLoad
{
[super viewDidLoad];
responseData =[[NSMutableData data]retain];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://XXXXXXX/XXXXX/filesCount.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{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"" message:#"DidFailWithError" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"response string is %#",responseString);
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
filesCount = [json objectWithString:responseString error:&error];
[responseString release];
NSLog(#"filesCount is %#",filesCount);
if (filesCount==nil) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"" message:#"Json parsing failed" delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[alert show];
}
else{
NSMutableString *text = [NSMutableString stringWithString:#"\n"];
for (int i = 0; i < [filesCount count]; i++)
[text appendFormat:#"%#\n", [filesCount objectAtIndex:i]];
NSLog(#"text is %s",[text UTF8String]);
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:text ]]];
NSData *addImageData = UIImagePNGRepresentation(img);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSRange lastComma= [text rangeOfString:#"/" options:NSBackwardsSearch];
NSString *requiredSubString = [text substringFromIndex:(lastComma.location+1)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:requiredSubString];
[fileManager createFileAtPath:savedImagePath contents:addImageData attributes:nil];
NSLog(#"Saved Document dir %#",savedImagePath);
UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:#"" message:#"files are downloaded" delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[alert1 show];
}
}
Please help me What wrong i mad.
I'm sorry, I really can't read your question very well. From what I see though you might benefit from looking at AFNetworking (https://github.com/AFNetworking/AFNetworking). It simplifies the process of downloading, and is rock-solid.
Look here for a nice tutorial: http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_afnetworking/
I am using the code in this question NSURLConnection download large file (>40MB) to download a KML file and load the data in my MKMap using the KMLViewer of Apple.KML files are small <200KB so KMLViewer is just fine.The code provided in the question should be fine too exept the fact that when the I click the button (that should make the request of the url and then load the data in the map) the map just goes to location 0,0 ,zooming tremendously and so all I can see is a black map.What is going wrong? What should I do?
Here is the code:
(By the way, I have two connections, because one uses JSON to get Google search results for locations from a UIsearchBar.)
EDIT 1
//In the ViewController.m
-(void) searchCoordinatesForAddress:(NSString *)inAddress //for Google location search
{
NSMutableString *urlString = [NSMutableString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#?output=json",inAddress];
[urlString setString:[urlString stringByReplacingOccurrencesOfString:#" " withString:#"+"]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0]; //webData in the header file
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if ( connection = theConnection ) //theConnection is created before
{
[webData appendData:data];
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
NSLog(#"Latitude - Longitude: %f %f", latitude, longitude);
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
[jsonString release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error !" message:#"Error has occured, please verify internet connection.." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
-(IBAction)showKmlData:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"KMLGenerator" ofType:#"kml"];
kml = [[KMLParser parseKMLAtPath:path] retain];
NSArray *overlays = [kml overlays];
[mapview addOverlays:overlays];
NSArray *annotations = [kml points];
[mapview addAnnotations:annotations];
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays) {
if (MKMapRectIsNull(flyTo)) {
flyTo = [overlay boundingMapRect];
} else {
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
mapview.visibleMapRect = flyTo;
}
EDIT 2 I have done modifications,now it doesn't go anywhere, it crashes because it doesn't find KMLGenerator.kml file (path)
-(void)showData
{
NSString *url = /*kmlStr;*/#"http://www.ikub.al/hartav2/handlers/kmlgenerator.ashx?layerid=fc77a5e6-5985-4dd1-9309-f026d7349064&kml=1";
NSURL *path = [NSURL URLWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:path];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
theConnection = connection;
[connection release];
[request release];
}
//Search Coordinates for address entered in the searchBar
-(void) searchCoordinatesForAddress:(NSString *)inAddress
{
NSMutableString *urlString = [NSMutableString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#?output=json",inAddress];
[urlString setString:[urlString stringByReplacingOccurrencesOfString:#" " withString:#"+"]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0]; //Here i get an alert: NSData may not respond to -setLength
//webData is a NSData object.
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data]; //Here i get an alert: NSData may not respond to -appendData
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ( connection == theConnection ) //"theConnection" is for kml file download
{
NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
}
else //it's a geocoding result
{
NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
//check the Google geocode error code before looking for coordinates...
NSDictionary *statusDict = [results objectForKey:#"Status"];
NSNumber *errorCode = [statusDict objectForKey:#"code"];
if ([errorCode intValue] == 200) //200 is "success"
{
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
NSLog(#"Latitude - Longitude: %f %f", latitude, longitude);
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
}
else
{
NSLog(#"geocoding error %#", errorCode);
}
[jsonString release];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"Error has occured, please verify internet connection..." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (IBAction)showKmlData:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"KMLGenerator" ofType:#"kml"];
kml = [[KMLParser parseKMLAtPath:path] retain];
NSArray *annotationsImmut = [kml points];
NSMutableArray *annotations = [annotationsImmut mutableCopy];
//[mapview addAnnotations:annotations];
[self filterAnnotations:annotations];
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
mapview.visibleMapRect = flyTo;
}
It's still hard to pinpoint the cause but there are some problems with the code you posted.
First, in didReceiveData, this line is probably not what you want:
if ( connection = theConnection ) //theConnection is created before
The single = is doing an assignment instead of an equality check (which is ==).
Fixing that, however, is not the solution (the other problem is in connectionDidFinishLoading).
The didReceiveData method is not the right place to process your geocoding JSON result. The didReceiveData method can be called multiple times for a single url request. So it's possible that the geocoding results (just like the kml file) may be delivered in multiple chunks which cannot be processed individually in that method. The data in that method may be a partial stream of the complete result which will not make sense to process. You should only be appending the data to an NSMutableData object or, as an answer to the linked question suggests, write the data to a file.
The data can only be processed/parsed in the connectionDidFinishLoading method.
Since you are using the same connection delegate for both the kml file download and the geocoding, they both call the same connectionDidFinishLoading method. In that method, you are not checking which connection it is being called for.
When the geocoding url request finishes and calls connectionDidFinishLoading, that method takes whatever is in webData (possibly the geocoding results or empty data) and writes it to the kmlStr file. This is probably what causes the kml data to show "nothing".
You have to move the processing of the geocoding results to connectionDidFinishLoading and check there what connection is calling it.
For example:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ( connection == theConnection ) //"theConnection" is for kml file download
{
NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
}
else //it's a geocoding result
{
NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
//check the Google geocode error code before looking for coordinates...
NSDictionary *statusDict = [results objectForKey:#"Status"];
NSNumber *errorCode = [statusDict objectForKey:#"code"];
if ([errorCode intValue] == 200) //200 is "success"
{
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
NSLog(#"Latitude - Longitude: %f %f", latitude, longitude);
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
}
else
{
NSLog(#"geocoding error %#", errorCode);
}
[jsonString release];
}
}
(It's probably better to avoid using the same delegate for multiple connections. It would be cleaner to move the geocoding out to another class with its own connection object and delegate methods. By the way, iOS5 has geocoding built-in so you don't need to do this yourself. See the CLGeocoder class.)
I added a check for the Google error code. It's possible the address queried returns no results in which case there will be no placemark coordinates in which case the latitude and longitude will get set to zero. This is another possible cause of the map going to 0,0.
It also seems you are using the deprecated v2 Google geocoder. This is the latest one but you may want to switch to using CLGeocoder instead unless you need to support iOS4 or earlier.
i want to get the list of venues nearby the current location
i found a method of forsquare Api
+(void)searchVenuesNearByLatitude:(NSString*)lat
longitude:(NSString*)lon
accuracyLL:(NSString*)accuracyLL
altitude:(NSString*)altitude
accuracyAlt:(NSString*)accuracyAlt
query:(NSString*)query
limit:(NSString*)limit
intent:(NSString*)intent
callback:(Foursquare2Callback)callback;
But i don't know how to use this method.
Any help would be appreciable.
I after studying the Foursquare Api Documentation.
I got the way of getting the Venues List Nearby current location.No need to Use pre-Built method of Foursquare Library(as I have shown in My Question.)
For This We need to make a HTTP request,By which we get JSON as response.
I have written the Code As below.
-(void)getVenuesList{
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
[dateFormatter setDateFormat:#"YYYYMMdd"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
//dateString it;s used for being UpTodate for API request
NSString* rediusMtr=#"2000";//distance under the comes
NSString *acess_Token=#"OAuth_Token ";
//acess_TokenOuth Token got from Foursqaure after registarting the App.
CGFloat latitude=245425435.564;//latitude & longitude coordinate
CGFloat longitude=245443435.564;
NSString *latitudeStr=[NSString stringWithFormat:#"%f,",latitude];
NSString *longitudeStr=[NSString stringWithFormat:#"%f",longitude];
NSMutableString*latitudeLongitudeString =[[NSMutableString alloc]initWithString:latitudeStr];
[latitudeLongitudeString appendString:longitudeStr];
NSString *query=#"airport";//Venuse to be searched.
NSString *resultLimit=#"50";//number of result to be returned.
NSString *URLString=[NSString stringWithFormat:#"https://api.foursquare.com/v2/venues/search?ll=%#&query=%#&limit=%#&radius=%#&oauth_token=%#&v=%#",latitudeLongitudeString,query,resultLimit,rediusMtr,acess_Token,dateString];
URLString =[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
//Perform request and get JSON back as a NSData object
NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if(error != nil) {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Done"otherButtonTitles:nil] autorelease];
[alert show];
}
else {
NSString *jsonString = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"%#",jsonString);
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil];
NSDictionary *responseData = [[jsonResponse objectForKey:#"response"] objectForKey:#"venues"] ;
NSArray *resultsArray= [responseData valueForKey:#"name"] ;
NSArray*distanceArray=[[responseData valueForKey:#"location"] valueForKey:#"distance"];
//Now we can use above resultsArray,distanceArray data.
}
For more Information about foursquare API go through this link
iam developing one application.In that i want to use the google places api.I written the url and established the connection like
NSURL *URL = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=true&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:URL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
But in did finish loading delegate method i cant get the data.That code is here.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc]initWithData:responseDataencoding:NSUTF8StringEncoding];
[responseData release];
SBJSON *parser = [[SBJSON alloc]init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:responseString error:nil];
}
So please tell me where i did the mistake.Why iam not getting the data.
Use ASIHTTPRequest framwork all these problems are automatically handle
all you have to do is just create a url
and parse the response using JSON framework
http://allseeing-i.com/ASIHTTPRequest/
According to my knowledge there are few mistaks.
NSString *responseString = [[NSString alloc]initWithData:responseDataencoding:NSUTF8StringEncoding];
The words responseData encoding are two world. I don't know whether you have pasted like that.
And I hope you have used -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegates to append data to responseData object.
I think you do not need to cast to NSDictionary. You can use following code.
NSString *content = [[NSString alloc] initWithBytes:[responseDate bytes] length:[responseDate length] encoding:NSUTF8StringEncoding];
NSLog(#"Data = %#", content);
NSError *error;
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *jsonD = [parser objectWithString:content error:&error];