#import
...
#define YANDEX_MAPS_API_DOMAIN @"http://geocode-maps.yandex.ru/1.x/"
...
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// Switching off location updates
[_locationManager stopUpdatingLocation];
// Reverse geocoding using Yandex Maps API
CLLocationCoordinate2D coordinate = newLocation.coordinate;
NSString *coordinatesString = [NSString stringWithFormat:@"%lf,%lf", coordinate.longitude, coordinate.latitude];
// Creating HTTP request. Here kind=locality means that we will be searching for a city.
NSString *urlString = [NSString stringWithFormat:@"%@?geocode=%@&results=1&lang=ru-RU&format=json&kind=locality", YANDEX_MAPS_API_DOMAIN, coordinatesString];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
// Sending synchronous request in background queue using dispatch queues
dispatch_queue_t backgroundQueue = dispatch_queue_create("bgQueue", nil);
dispatch_async(backgroundQueue, ^{
__autoreleasing NSHTTPURLResponse *urlResponse = nil;
__autoreleasing NSError *error = nil;
NSData *resultData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&error];
// Parsing a result
if (! error) {
NSLog(@"Status Code: %d %@", [urlResponse statusCode], [NSHTTPURLResponse localizedStringForStatusCode:[urlResponse statusCode]]);
NSString *resultString = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
// NSLog(@"resultString:%@", resultString);
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSDictionary *jsonObject = [jsonParser objectWithString:resultString];
// If count is zero, then region is not found
int count = [jsonObject[@"response"][@"GeoObjectCollection"][@"metaDataProperty"][@"GeocoderResponseMetaData"][@"found"] integerValue];
if (count == 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self showRegionNotFoundError];
});
return;
}
// Searching in a JSON
NSString *city = [jsonObject[@"response"][@"GeoObjectCollection"][@"featureMember"] firstObject][@"GeoObject"][@"name"];
NSLog(@"Yandex API City returned: %@", city);
dispatch_async(dispatch_get_main_queue(), ^{
// Here I have a code that updates my UI after city is determined
});
}
else {
// If failed to get data from Yandex API
NSLog(@"An error occured, Status Code: %i", urlResponse.statusCode);
NSLog(@"Description: %@", [error localizedDescription]);
NSLog(@"Response Body: %@", [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]);
dispatch_async(dispatch_get_main_queue(), ^{
[self showRegionNotFoundError];
});
}
dispatch_async(dispatch_get_main_queue(), ^{
[self hideSpinner];
});
});
}