Getting the address based on latitude and longitude of multiple points - ios

I'm trying to loop through an array of about 10 latitude and longitude values and get the address from them. I created a console application using Xcode and I'm able to loop the file and retrieve the locations, add them to an NSMutableArray and pass it to the below function. However the completion handler block never gets called. What could I be doing wrong? Let me know if you need to see any other code at this point. I'm just frustrated and confused and wonder what could it be.
void nextGeocodeRequest(int start, NSMutableArray * myLocations)
{
#autoreleasepool {
for (int i = start; i < 1; i++) {
[ myLocations objectAtIndex:i ];
double mylong = [[[myLocations objectAtIndex:i] valueForKey:#"Longitude"] doubleValue ];
double mylat = [[[myLocations objectAtIndex:i] valueForKey:#"Latitude"] doubleValue];
goal = [[CLLocation alloc] initWithLatitude: mylat longitude:mylong] ;
CLGeocoder * geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:goal completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
NSLog(#"this is the state '%#'",placemark.locality);
/*
self.state = [[State alloc] init];
self.state.name = placemark.locality;
self.state.code = placemark.administrativeArea;
self.state.stateId = 1;
self.state.stations = 300;
[self.states addObject:self.state];
*/
//[self.tableView reloadData];
nextGeocodeRequest(i, myLocations);
} else {
NSLog(#"%#", error.debugDescription);
}
}];
} //ends the for
// return 0;
}
}

You need to run the current NSRunLoop at the end of your main function such that the geocoding connections will be processed. You then need to define how your app will terminate after all of the connections are processed.
[[NSRunLoop currentRunLoop] run];
(put this at the end of the auto release pool in your main function)
Currently your app does all of the inline processing, prepares a number of connections with nothing to process them and then simply exits.

Related

Get Location name from reverseGeocodeLocation

I want to find out photos location using reverseGeocodeLocation. I use the below function
#interface GalleryPhotosViewController ()
{
CLPlacemark *placemark;
}
#end
-(NSString *)getLocation:(CLLocation *)locations{
CLGeocoder *geocoder = [CLGeocoder new];
[geocoder reverseGeocodeLocation:locations completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
placemark = [placemarks lastObject];
}];
return placemark.name;
}
I could not get that name when call the function but I get that after execution of other parts of code. I know that reverseGeocodeLocation has a completion block, it is handed off to another thread when execution reaches it. But I need to get that name when call the function. I go through many solutions but could not solve my problem.
I want to receive location name in currentLocation.
CLLocation *loc = asset.location;
NSString *currentLocation = [self getLocation:loc];
Where should I change my code. Please help.
This is because you are returning value before you get it in completion handler of reverseGeocodeLocation. Now, you can't return the value from any completion block so what you need to do is create your own completionblock and call it when you get your result something like,
-(void)getLocation:(CLLocation *)locations withcompletionHandler : (void(^)(NSString *name))completionHandler{
CLGeocoder *geocoder = [CLGeocoder new];
[geocoder reverseGeocodeLocation:locations completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
placemark = [placemarks lastObject];
completionHandler(placemark.name);
}];
}
and call it like,
[self getLocation:location withcompletionHandler:^(NSString *name) {
NSLog(#"your name : %#",name); // or do whatever you want with name!
}];
Update :
If you want whole array in completion handler as you have mentioned in comment then your method should be like,
-(void)getLocation:(CLLocation *)locations withcompletionHandler : (void(^)(NSArray *arr))completionHandler{
CLGeocoder *geocoder = [CLGeocoder new];
[geocoder reverseGeocodeLocation:locations completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks,
NSError * _Nullable error) {
// placemark = [placemarks lastObject];
completionHandler(placemarks);
}];
}
and you can call it like,
[self getLocation:location withcompletionHandler:^(NSArray *arr) {
// you will get whole array here in `arr`, now you can manipulate it according to requirement
NSLog(#"your response array : %#",arr);
CLPlacemark *placemark = [arr lastObject];
}];
The method reverseGeocodeLocation of class CLGeocoder runs asynchronously hence you will not get the location data as a return value from the called function. It uses the completion handler where the location data is returned and you can use that completion handler block to update the UI or any further processing of your location data.
Get city,state and address you have to pass latitude and longitude,
so pass latitude and longitude will pass to geocoder block and
within block you will placemarks array.
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocation *myLocation = [[CLLocation alloc]initWithLatitude:23.0225
longitude:72.5714];
[geocoder reverseGeocodeLocation:myLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(#"Geocode failed with error: %#", error);
return;
}
if (placemarks && placemarks.count > 0)
{
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary =
placemark.addressDictionary;
NSLog(#"%# ", addressDictionary);
NSString *address = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [addressDictionary
objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *state = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStateKey];
NSLog(#"%# %# %# %#", address,city, state);
}
}];

iOS Location Reminder App misses certain location

We are building location based reminder app and it works in 7 case out of 10. It simply misses certain locations. Can you please suggest what would be the possible issue with that?
Following is the logic we are using for location matching.
-(void)locationChangeLogic {
CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:latitudeTemp longitude:longitudeTemp];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Perform long running process
NSArray *arrayLocations = [[NSArray alloc] initWithArray:[[self db] getListOfLocations]];
NSMutableArray *arrayToNotification = [[NSMutableArray alloc] init];
if ([arrayLocations count] > 0) {
for (NSDictionary *dict in arrayLocations) {
CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:[[dict valueForKey:#"latitude"] floatValue] longitude:[[dict valueForKey:#"longitude"] floatValue]];
float miles = [[NSUserDefaults standardUserDefaults] floatForKey:#"miles"];
CLLocationDistance distance = [currentLocation distanceFromLocation:newLocation];
//Set matched objects and update flag
if ((distance/1609.344) <= miles) {
if ([[dict valueForKey:#"isSelected"] integerValue] == 1) {
[arrayToNotification addObject:dict];
}
//Matched location FLAG will going to 0, so notification not get fire twice or repeatedly
}else {
//The location which are not in current redius, we will make those location FLAG to 1, So when user enter in different location it will check for that
}
}
}
dispatch_async(dispatch_get_main_queue(), ^{
if ([arrayToNotification count] > 0) {
[self setAndFireLocalNotifications:arrayToNotification];
}
});
});
}
Any help would be appreciated.

Geocoding to UITextfield not displaying

I am using reverse geocoding which works but I am trying to separate the attributes. For example I want to have zip code displayed in it's own text field.
This is what I've tried but I get a breakpoint at if([placemarks count] >0)
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// Make sure this is a recent location event
CLLocation *newLocation = [locations lastObject];
NSTimeInterval eventInterval = [newLocation.timestamp timeIntervalSinceNow];
if(abs(eventInterval) < 30.0)
{
// Make sure the event is valid
if (newLocation.horizontalAccuracy < 0)
return;
// Instantiate _geoCoder if it has not been already
if (_geocoder == nil)
_geocoder = [[CLGeocoder alloc] init];
//Only one geocoding instance per action
//so stop any previous geocoding actions before starting this one
if([_geocoder isGeocoding])
[_geocoder cancelGeocode];
[_geocoder reverseGeocodeLocation: newLocation
completionHandler: ^(NSArray* placemarks, NSError* error)
{
if([placemarks count] > 0)
{
CLPlacemark *foundPlacemark = [placemarks objectAtIndex:0];
self.address.text =
[NSString stringWithFormat:#"%#",
foundPlacemark.description];
self.zip.text =
[NSString stringWithFormat:#"%#",
foundPlacemark.postalCode];
}
else if (error.code == kCLErrorGeocodeCanceled)
{
NSLog(#"Geocoding cancelled");
}
else if (error.code == kCLErrorGeocodeFoundNoResult)
{
self.address.text=#"No geocode result found";
}
else if (error.code == kCLErrorGeocodeFoundPartialResult)
{
self.address.text=#"Partial geocode result";
}
else
{
self.address.text =
[NSString stringWithFormat:#"Unknown error: %#",
error.description];
}
}
];
Try to handle error first by checking if its nil:
if (error) {
// handle here
NSLog(#"error: %#", error);
return; // exit statement
}
// handle code here if there was no error
and avoid strong reference cycles create a weak object of your self, when calling a object use this instnace.
__weak typeof(self) weakSelf = self;
so self.address.text=#"Partial geocode result"; will turn to weakSelf.address.text=#"some text here...";

Cannot AddObject to NSMutableArray from Block

I have a feeling that my problem here is really with blocking, but maybe it's something else too. I am trying to forward geocode an address and place the coordinates into an array to use later.
An exception is raised down at the bottom when I try to call on one of the objects I tried added to the array in the block. The exception also gets raised before any of the NSLogs ever print out within the block text.
What's the proper way to handle this? Thanks.
- (NSMutableArray *)convertAddressToGeocode:(NSString *)addressString
{
//return array with lat/lng
__block NSMutableArray *coordinates = [[NSMutableArray alloc] initWithCapacity:0];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:addressString
completionHandler:^ (NSArray* placemarks, NSError* error) {
for (CLPlacemark* aPlacemark in placemarks)
{
// Process the placemark.
if (error){
NSLog(#"Geocode failed with error: %#", error);
[self displayError:error];
return;
}
else {
NSArray const *keys = #[#"coordinate.latitude",
#"coordinate.longitude",
#"altitude",
#"horizontalAccuracy",
#"verticalAccuracy",
#"course",
#"speed",
#"timestamp"];
NSString *keylat = keys[0];
NSString *keylng = keys[1];
if (aPlacemark.location == nil)
{
NSLog(#"location is nil.");
}
else if ([keylat isEqualToString:#"coordinate.latitude"] && [keylng isEqualToString:#"coordinate.longitude"])
{
NSString *lat = #"";
NSString *lng = #"";
lat = [self displayStringForDouble: [aPlacemark.location coordinate].latitude];
lng = [self displayStringForDouble: [aPlacemark.location coordinate].longitude];
NSLog(#"This never gets executed"): //THIS NEVER GETS EXECUTED
[coordinates addObject:[NSString stringWithFormat:#"%#",lat]];
[coordinates addObject:[NSString stringWithFormat:#"%#",lng]];
}}}}];
NSLog(#"Array: %#", coordinates[0]); //EXCEPTION RAISED HERE, Nothing ever gets added
return coordinates;
}
Here is the code this method is supposed to be plugged into, but I'm not getting the coordinates out of convertAddresstoGeocode to pass to convertCoordinatestoRepModel:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *addressToSearch = self.addressSearchField.text;
NSMutableArray *coordinateArray = [self convertAddressToGeocode:addressToSearch];
NSMutableArray *repModelArray = [self convertCoordinatesToRepModel:coordinateArray];
...
}
if geocodeAddressString is async operation than your block will be performed after
NSLog(#"Array: %#", coordinates[0]);
also, after call of your method ends (when event already handled) the coordinates array
released (it is because of __block modifier - blocks do not retain objects with __block modifier), and in your block you try to use dealloced coordinates array.
Once again:
Your block will be called after NSLog(#"Array: %#", coordinates[0]);
f.e.:
Remove NSLog(#"Array: %#", coordinates[0]); - it is normal that in that moment array is empty.
Store your coordinates array in some #property , you can release it after using in block
UPDATE:
in .h file
typedef void (^ConverteArrayCallback)(NSArray *coordinates);
under #intrerface
- (void)convertAddressToGeocode:(NSString *)addressString callback:(ConverteArrayCallback) callback;
in .m file
- (void)convertAddressToGeocode:(NSString *)addressString callback:(ConverteArrayCallback) callback {
NSMutableArray *coordinates = [[NSMutableArray alloc] initWithCapacity:0];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:addressString
completionHandler:^ (NSArray* placemarks, NSError* error) {
for (CLPlacemark* aPlacemark in placemarks)
{
// Process the placemark.
if (error){
NSLog(#"Geocode failed with error: %#", error);
[self displayError:error];
return;
}
else {
NSArray const *keys = #[#"coordinate.latitude",
#"coordinate.longitude",
#"altitude",
#"horizontalAccuracy",
#"verticalAccuracy",
#"course",
#"speed",
#"timestamp"];
NSString *keylat = keys[0];
NSString *keylng = keys[1];
if (aPlacemark.location == nil)
{
NSLog(#"location is nil.");
}
else if ([keylat isEqualToString:#"coordinate.latitude"] && [keylng isEqualToString:#"coordinate.longitude"])
{
NSString *lat = #"";
NSString *lng = #"";
lat = [self displayStringForDouble: [aPlacemark.location coordinate].latitude];
lng = [self displayStringForDouble: [aPlacemark.location coordinate].longitude];
NSLog(#"This never gets executed"): //THIS NEVER GETS EXECUTED
[coordinates addObject:[NSString stringWithFormat:#"%#",lat]];
[coordinates addObject:[NSString s
tringWithFormat:#"%#",lng]];
}}}
if (callback != NULL) {
callback(coordinates);
}
}];
}
That should works!
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *addressToSearch = self.addressSearchField.text;
[self convertAddressToGeocode:addressToSearch callback:^(NSArray *coordinates)
{
self.textView.text = [coordinates objectAtIndex:0];
}];
}
__block NSMutableArray *coordinates = [[NSMutableArray alloc] initWithCapacity:0];
The problem is here; just replace the above code with:
NSMutableArray *coordinates = [[NSMutableArray alloc] init];

Why is this CLLocationCoordinate2D variable unassignable?

I have a geocoder method and I want it to return the CLLocationCoordinate2D that it generates for me.
- (CLLocationCoordinate2D)geocode{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(0,0);
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
coordinate = location.coordinate;
} else {
NSLog(#"error");
}
}];
return coordinate;
}
The line coordinate = location.coordinate produces an error however. XCode says coordinate is an unassignable variable. Anyone see what I'm doing wrong?
update:
After following sebastian's advice, I got the code to compile, however, coordinate is not being properly set. If you take a look at both of the NSLog statements i put in the method, the first one prints out the correct coordinates that I need assigned to coordinate, however as soon as the if statement exits, coordinate goes back to being set to (0,0). The second NSLog statement prints (0,0). Anyone know how I can fix this?
- (CLLocationCoordinate2D)geocode{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
__block CLLocationCoordinate2D geocodedCoordinate = CLLocationCoordinate2DMake(0,0);
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
geocodedCoordinate = location.coordinate;
NSLog(#"%f, %f", coordinate.longitude, coordinate.latitude);
} else {
NSLog(#"error");
}
}];
NSLog(#"%f, %f", coordinate.longitude, coordinate.latitude);
return coordinate;
}
You have to use the __block keyword if you want to assign to a variable that was defined outside the block's scope:
__block CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(0,0);
Have a look at the Blocks and Variables section of Apple's Block Programming Topics
About the variable not getting set when it compiles:
geocodeAddressDictionary:completionHandler: runs asynchronously. That means it returns immediately but the block gets executed later, when the results are available. You need to change the way you call your methods. At the moment you are probably doing something like this
self.myCoordinate = [self geocode];
What you have to do is more like this:
- (void)geocode{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
self.myCoordinate = location.coordinate;
NSLog(#"%f, %f", coordinate.longitude, coordinate.latitude);
} else {
NSLog(#"error");
}
}];
}
Running [self geocode] returns immediately and myCoordinate will be set when the block runs.
If you are doing it that way, note that this could lead to a reference cycle, because self is being retained by the block.

Resources