nearby venue to iphone into simple array - iphone

Im really having a hard time figuring this out. Ive read a bunch of PDFS and stackoverflow questions on this but I have never used and API and can't quiet get it.
I am trying to get my longitude and latitude coordinates and use any API out there (foursquare, google maps, any others you can recommend that are free?) to get a list of nearby parks and just put it into an NSMutableDictionary key=name object=#"distance". No need to get all its content, just distance and name. But I have been stuck on the first part, getting my longitude and latitude coordinates for over 4 hours. Can anyone show me code wise how I would get my coordinates, no need to explain how to parse the API, once i have my coordinates I feel like I can figure that out. Ive downloaded apples locateme source code but still cant get it to work on mine. Is there maybe a set of easy to follow steps or code someone can provide that I can just use and get this headache over with? Ive imported the location framework. Is there a quick 10-20 lines of code to solve this, not 3 additional view controllers with so much I dont quiet understand.
Thanks a lot

- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
#pragma mark Current location methods
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
latit = newLocation.coordinate.latitude;
longit = newLocation.coordinate.longitude;
NSLog(#"latitude = %f",latit);
NSLog(#"longitude = %f",longit);
[manager stopUpdatingLocation];
[self getNearByList];
}
-(void)getNearByList
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd"];
NSString *currentDate = [dateFormat stringFromDate:[NSDate date]];
[dateFormat release];
NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:#"https://api.foursquare.com/v2/venues/search?ll=%f,%f&client_id=YOUR_CLIENT_ID_HERE&client_secret=YOUR_CLIENT_SECRET_HERE&v=%#&limit=100&radius=2000&categoryId=4bf58dd8d48988d1e0931735,4bf58dd8d48988d176941735,4bf58dd8d48988d1ed941735,4bf58dd8d48988d119951735,4bf58dd8d48988d123941735,4d954afda243a5684865b473,4edd64a0c7ddd24ca188df1a,4bf58dd8d48988d1c9941735,4bf58dd8d48988d1bd941735,4bf58dd8d48988d124951735,4bf58dd8d48988d115951735,4bf58dd8d48988d11a951735,4bf58dd8d48988d10c951735,4bf58dd8d48988d11b951735,4bf58dd8d48988d11e951735,4bf58dd8d48988d1f9941735,4bf58dd8d48988d1f5941735,4bf58dd8d48988d113951735,4f04afc02fb6e1c99f3db0bc,4bf58dd8d48988d110951735,4bf58dd8d48988d1f2941735,4bf58dd8d48988d1fd941735,4bf58dd8d48988d103951735,4bf58dd8d48988d104941735,4f04aa0c2fb6e1c99f3db0b8,4d1cf8421a97d635ce361c31,4bf58dd8d48988d1f8941735,4d4b7105d754a06374d81259,4bf58dd8d48988d16d941735,4bf58dd8d48988d128941735,4bf58dd8d48988d111951735,4bf58dd8d48988d1ca941735,4bf58dd8d48988d117951735,4bf58dd8d48988d107951735,4bf58dd8d48988d1fa941735,4bf58dd8d48988d118951735,4bf58dd8d48988d17f941735,4bf58dd8d48988d1ac941735,4bf58dd8d48988d180941735",latit,longit,currentDate] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; //YOU CAN FOUND MORE CATEGORY ID AT FOURSQURE WEBSITE..
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 30.f];
NSLog(#"url = %#",urlRequest);
webData1 = [[NSMutableData data] retain];
urlConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData1 setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData1 appendData:data];
//NSLog(#"webData1 = %#",webData1);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Error"
message : #"An error has occured."
delegate:nil
cancelButtonTitle :#"OK"
otherButtonTitles :nil];
[alert1 show];
[alert1 release];
[webData1 release];
[connection release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *data = [[NSString alloc] initWithBytes: [webData1 mutableBytes] length:[webData1 length] encoding:NSUTF8StringEncoding];
NSLog(#"data = %#",data);
[connection release];
[webData1 release];
}

Use Google Place Api.You just need to register and than you will get key for api
//example api. This api will give you food in your defined radius of longitude and latitude in the json data format
https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere
Google Place API
Hope, this will help you..enjoy...

Related

how to data fetch using json parsing in ios

I am beginner of iPhone developer. I want to display data from server I have used below source code..
-(void)loadData:(id)sender
{
self.requestdata=[NSMutableData data];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:kLatestKivaLoansURL]];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[requestdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[requestdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
self.requestdata=nil;
}
#pragma mark-
#pragma process loan data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responsedata=[[NSString alloc]initWithData:requestdata encoding:NSUTF8StringEncoding];
self.requestdata=nil;
NSDictionary *respDict = [[responsedata JSONValue]objectForKey:#"nodes"];
NSLog(#"Response Dict:%#",respDict);
NSMutableArray *arraY = [[NSMutableArray alloc]init];
arraY = [respDict mutableCopy];
NSLog(#"My array:%#",arraY);
NSString *mystr = [[[arraY objectAtIndex:0]valueForKey:#"node"]valueForKey:#"field_company_name_value"];
NSLog(#"Mystrname:%#",mystr);
NSArray *latestLoans=[(NSDictionary *)[responsedata JSONValue]objectForKey:#"responseData"];
NSLog(#"latest_dictionary:%#",latestLoans);
DisplayViewController *disp=[[DisplayViewController alloc]init];
for (int i = 0; i< [[latestLoans valueForKey:#"entries"] count] ; i++) {
// Search *aSearches = [[Search alloc] init];
NSDictionary *tempDict = [[latestLoans valueForKey:#"entries"] objectAtIndex:i];
// disp.link=[tempDict valueForKey:#"link"];
/*link = [tempDict valueForKey:#"link"];
aSearches.title = [tempDict valueForKey:#"title"];
aSearches.description = [tempDict valueForKey:#"contentSnippet"];
[appDelegate.search addObject:aSearches];*/
[appDelegate.disparray addObject:tempDict];
}
NSLog(#"DisplayArray:%#",appDelegate.disparray);
[self.view addSubview:disp.view];
/* DisplayViewController *disp=[[DisplayViewController alloc]initWithNibName:#"DisplayViewController" bundle:nil];
[self.navigationController pushViewController:disp animated:YES];*/
}
Please give any suggestion or source code which is apply in my code
Take a look at AFNetworking. It will do the job for you.
There is a specific method to handle JSON operations through the class AFJSONRequestOperation
Hope it helps.
http://www.touch-code-magazine.com/how-to-fetch-and-parse-json-by-using-data-models/
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
http://json.org/
This is great tutorial for beginner, pls read this tutorial.

iPhone SDK MKPlacemark

I need help with the MapKit framework. I am new to iPhone development.
I have a webview that loads from a url with 3 params like this:
in viewDidLoad method from the view controller:
NSString *hoUrlString = [NSString stringWithFormat:#"http://fastenergy.clavis-solutions.de/?iwidth=%#&iheight=%#&zipcode=%#", hString, wString, zipcode];
I can't get the zipcode. I am calling this before the url:
locationController = [[HoCLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
and in this method from HoCLController.m
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
, I call
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:coord];
[geocoder setDelegate:self];
[geocoder start];
Then I have these 2 methods
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
NSLog(#"The geocoder has returned: %#", placemark.postalCode);
}
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
NSLog(#"Error: %#", [error description]);
}
The question is , how can I get the zipcode in the url?
Thank you and please help.
You have already the answer in your question.
placemark.postalcode consists of your zipcode.
Just make sure, that all your variables consist the right value.
zipcode = placemark.postalCode;
Should be the answer, if i get your question right.
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:coord];
You have to pass coordinate in this method. So check if coord is not nil.I guess this is what you want.
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
Oh Ok, forget it..
I miss something, sorry
Are you subclassing CLLocationManager ???
If not, why are you allocating like this: locationManager = [[HoCLController alloc] init]; instead of this:self.locationManager = [[CLLocationManager alloc] init]; I'm sorry if I'm getting something wrong, but think i'm giving you the answer..

How to retrieve current city name using wifi/3g ip address with iPhone/iOS programming (Objective-c)?

I want to retrieve the current "city name" of the iPhone using ip address of device (wifi/3g). Is there any way to do it? please help me out.
Following is the place where I want the current location.
-(BOOL)fetchAndParseRss{
NSString * CurrentLocation = <I want the retrieved Location here!!>;
NSString * URLrss = [NSString stringWithFormat:#"http://news.google.com/news?q=location:%#&output=rss", CurrentLocation];
NSURL *url = [NSURL URLWithString:URLrss];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
}
Actually i am developing an app for myself that displays the news of current city.
You can use CLLocationManager and MKReverseGeocoder to get users city.
First add CLLocationManager and start updating user location
- (void)startLocationManager
{
if (locManager==nil)
locManager = [[CLLocationManager alloc] init];
if (locManager.locationServicesEnabled)
{
NSLog(#"User has opted out of service on it error");
} else {
locManager.delegate = self;
locManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locManager startUpdatingLocation];
}
}
Then add location manager delegate methods to use MKReverseGeocoder.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"Manager error: %#", [error description]);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
[geocoder release];
geocoder.delegate = self;
[geocoder start];
[manager stopUpdatingLocation];
}
and of course you have to implement MKReverseGeocoder Delegate methods
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(#"reverseGeocoder:%# didFailWithError:%#", geocoder, error);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
// with the placemark you can now retrieve the city name
NSString *city = [placemark.addressDictionary objectForKey:#"City"];
NSLog(#"City is %#", city);
}
This method can be use if user gives permission to your application for location manager.
One option would be to make an HTTP request to a website like geoiptool.com and scrape the city information from the response. I'm unsure how much success you'll have when using mobile phone networks, though—wifi worked when I tried it on my phone, but 3G didn't.

EXC_BAD_ACCESS issue on iphone and simulator

I am getting an EXC_BAD_ACCESS out side of my own code. Currently my code gets a URL through a shareURLCache object and then starts url connection. Once I leave the method that starts the url connection I hit the EXC_BAD_ACCESS. I have tried using instruments to find any zombies and I have analysed for memory leaks and not turned up either. At this point I am completely stuck.
Here is the code that loads the url and starts the url connection
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"At new location: %#",newLocation);
MKCoordinateRegion region =
MKCoordinateRegionMakeWithDistance([newLocation coordinate], 750, 750);
[mapView setRegion:region animated:YES];
[location stopUpdatingLocation];
CLLocationCoordinate2D coord = [newLocation coordinate];
NSURL *url = [urlCache getReccomendationForUID:#"12345" atLat:coord.latitude
atLon:coord.longitude forCategories:nil];
// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
if (connection) {
// Create the NSMutableData to hold the received data.
// xmlData is an instance variable declared elsewhere.
xmlData = [[NSMutableData alloc]init];
} else {
NSLog(#"Could not create connection");
}
}
Method from the sharedURLCache that returns the url
-(NSURL *)getReccomendationForUID:(NSString *)u atLat:(double)lat atLon:(double)lon forCategories:(NSArray *)cat
{
if(remote) {
NSMutableString *categories = [[NSMutableString alloc]init];
for(NSString *s in cat) {
[categories appendString:#"&cat="];
[categories appendString:s];
}
NSString *s = [NSString stringWithFormat:#"%#/recommendation?uid=%#&psw=null&lat=%f&lon=%f?%#",
apiRoot,u,lat,lon,categories];
[categories release];
return [NSURL URLWithString:s];
} else {
return [[NSBundle mainBundle] URLForResource:#"XMLTest" withExtension:#"xml"];;
}
}
Just start by commenting out code and running to see if you can get the mem error to disappear then start adding code again until it appears, then you have a better idea where the issue is. it could be anywhere in your code since you seem to have a number of objects in there that are not passed in e.g. 'location'.
[location stopUpdatingLocation];
I had same memory issue with
[mapView setRegion:region animated:YES];
This method doesn't like fast updates...

Sharing data between two classes

this is my first iPhone application and I'm using JSON framework to decode JSON sent from a server.
I insert the data in a NSMutableArray from an AppDelegate file.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
responseData = [[NSMutableData data] retain];
museums = [[NSMutableArray alloc] init];
viewController = [[RootViewController alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://my_json_link"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
return YES;
}
- (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];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *data = (NSDictionary *)[json objectWithString:responseString error:&error];
[responseString release];
if (data == nil)
NSLog(#"JSON parsing failed: %#", [error localizedDescription]);
else {
for (NSDictionary *item in data) {
// Read the data
NSString *aName = [item objectForKey:#"name"];
NSString *aDescription = [item objectForKey:#"description"];
// Create a new museum object with the data from json
Museum *museum = [[Museum alloc] initWithName:aName description:aDescription];
// Add the museum object to the Array
[museums addObject:museum];
[museum release];
}
}
viewController.museums = museums;
}
The museums array is not empty inside connectionDidFinishLoading function, but I can't see it when I try to print it in RootViewController.
I tried to set the array in the line
viewController.museums = museums;
but I didn't understand what is wrong.
I can fix the problem only if I move these lines:
[window addSubview:viewController.view];
[window makeKeyAndVisible];
from the first function to connectionDidFinishLoading function. But in this case doesn't work the other view when I click one record of the table.
Thanks for any help.
viewController = [[RootViewController alloc] init];
First, I need you to make sure that the viewController you create in didFinishLaunching... is actually the correct viewController. Have you actually wired up that instance to be what you think it is or do you two instance os RootViewController?
Second if you are actually setting museums on the right instance of RootViewController you need to make sure that your timing is correct. This means that are you setting museums BEFORE you trying to print it out in viewController
--Edit--
OK since we established that things are happening in the wrong order you should try and reload the table. The UITableView has a method called reloadData that will take care of this for you and you need to call this everytime you change the data source after the table has been created.
So in RootViewController add a method called reload which in turn calls reloadData on your UITableView and modify your code:
viewController.museums = museums;
[viewController reload];
You could add to your view controller, temporarily just for debugging:
-(void) setMuseums:(NSMutableArray*)m {
self->_museums = [m retain];
}
and then add a breakpoint in there. Make sure it's getting hit, or maybe there's something later coming along and setting it to nil.
The Museums property is declared as #property (nonatomic, retain) NSMutableArray *museums; right?
Try to put a NSLog inside the for loop and check if it is executed.
try using
viewController.museums = [museums retain];