How to get Venues list Using FourSquare Api - objective-c++

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

Related

Not getting json response in google query of longitude and latitude in iOS?

I am new to iOS, so if any help it will be appreciated.
I am trying to get the longitude and latitude from address, earlier the code was working fine but now the JSON data are coming null.
Here my sample code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"my Coordinate : %#",returnString);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
But i am getting the output as null.
So please help me out.
Thanks!
Thanks for your replies that all make me learn a lots.
As one of my friend just tell me the solution so i am sharing with you.
Here is the code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *locationResult = [parser objectWithString:returnString];
//[reverseGeoString copy]`
And its working fine.
But still there is a question that why this happen.As earlier that code is working fine but it suddenly stopped working.
You must construct your returnString in the following method that actually receives the data:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
Check out this for additional information on how to use NSURLConnection and the delegate methods.
I would say you're missing the all-important "REQUEST"...
This is what I do. Hope it helps:
NSString *encodedAddress = (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge_retained CFStringRef)searchBar.text, NULL, (CFStringRef) #"!*'();:#&=+$,/?%#[]",kCFStringEncodingUTF8 );
NSString* searchURL = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true",encodedAddress];
NSError* error = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:searchURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error){
NSLog(#"Error performing request %#", searchURL);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (jsonString!=nil){
NSLog(#"%#",jsonString);
}

FourSquare request returns null string in iOS

I have looked everywhere and can't seem to find a solution. I am using ASIHTTPRequest to tap into the FourSquare API in my iOS app. However, when I try to print the JSON string that I expect to be returned to me, I am getting "null". If I navigate to the same request URL in a browser, I get a whole slew of JSON. Here is my code...
- (void)fetchFoursquareLocationsUsingLocation:(CLLocation *)location {
// First, let's build our request
CLLocationDegrees latitude = location.coordinate.latitude;
CLLocationDegrees longitude = location.coordinate.longitude;
NSString *foursquareURLString = [NSString stringWithFormat:#"https://api.foursquare.com/v2/venues/search?ll=%0.6f,%0.6f&client_id=%#&client_secret=%#&v=20120103",
latitude,
longitude,
FOURSQUARE_CLIENT_ID,
FOURSQUARE_CLIENT_SECRET];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:foursquareURLString]];
self.foursquareData = [[NSMutableData alloc] init];
request.delegate = self;
[request startAsynchronous];
}
#pragma mark - ASIHTTPRequest Delegate
- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data {
[self.foursquareData appendData:data];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSString *jsonCheck = [[NSString alloc] initWithData:self.foursquareData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonCheck);
}
UPDATE: Thanks to #Kamarshad's SO post How to get Venues list Using FourSquare Api, I was able to get valid JSON back. The difference being I made the request asynchronously such that
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:foursquareURLString]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//
if (error != nil) {
NSLog(#"Something went wrong...%#", [error localizedDescription]);
}
else {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
}
}];
What is it about the ASIHTTPRequest that keeps a valid response from coming back??
This is happenning beacuse your are not passing the the V(date) value correctly at the time of Request you just pass the static(old) which may not work after that date.
You will have to pass the Updated(current) V(date) in URL String i.e V should be the CurrentDate in which you are makingRequest to FourSquare.
Try Below Code and Use again.
Update: One Thing More You should pass some thing to be search
Because in your Request you are not passing any search query
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* rest=#"street"
// To be Search
MakeRequest As Below and Rest of The Code will be same as you used.
NSString *foursquareURLString = [NSString stringWithFormat:#"https://api.foursquare.com/v2/venues/search?ll=%0.6f,%0.6f&client_id=%#&client_secret=%#&v=%#&query=%#",
latitude,
longitude,
FOURSQUARE_CLIENT_ID,
FOURSQUARE_CLIENT_SECRET,dateString,rest];
//Convert the Special characters into escapes.
foursquareURLString =[foursquareURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:foursquareURLString]];
//Rest will be same
For More Detail About the FourSquare API endpoints go Through This Link
I Hope It'll give you the Correct Result Instead of the Null !!!!!!!.

Use of undeclared identifier in json for iOS

I am getting a use of undeclared identifier error in my json but I am following the example from http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
how do I fix this? Yes I am very new to objective-c \ ios :) Thanks
I am putting this code in my view based application in my viewcontroller.m file
The issue is with "SBJSON *parser = [[SBJSON alloc] init];"
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"text"], [[status objectForKey:#"user"] objectForKey:#"screen_name"]);
}
Try changing the line to SBJsonParser *parser = [[SBJsonParser alloc] init];
Edit:
A way that can be easier is to use the NSString category that SBJSON provides:
NSArray *statuses = (NSArray *)[json_string JSONValue];

How to read the JSON value on console in iphone

i have the following json value in console:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
this is my server api :#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"
//api takes 5 parameters .
when i post data to server api values are posted to server and i get the above response in json format.
i want to parse the above the JSON value that i get in the response and save in sqlite database.
i am doing this code to parse the above JSON value:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
You should check out some of the JSON parsers, my personal favourite is json-framework. After you've included one of them in your project, where you've got your JSON response from your server:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:#"Result"];
which will return your array of results (where each object in the array is an NSDictionary).
You can save this to a database with the help of a model class, Result
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:#"UserId"];
result. FirstName = [value objectForKey:#"FirstName"];
...
[results addObject:result];
[result release];
}
use the array of results to save it to the database.
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}

XML Parsing - NSXMLParserErrorDomain error 5

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?