I have a block of code that adds an object to an array declared outside the block with the "__block" notation (it's an ivar). However, once the block is exited, the array contains no values. I know that it isn't trying to add empty strings to the array, because my console prints the strings correctly. Any help would be appreciated. Here is my code:
addressOutputArray = [[NSMutableArray alloc] init];
for(CLLocation *location in locationOutputArray)
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
{
if(placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
NSString *address = [NSString stringWithFormat:#"%# %#,%# %#", [topResult subThoroughfare],[topResult thoroughfare],[topResult locality], [topResult administrativeArea]];
[addressOutputArray addObject:address];
NSLog(#"%#",address);
}
}];
[geocoder release];
}
NSLog(#"Address output array count: %d", [addressOutputArray count]);
The final log gives me a count of zero. Any help at all would be really appreciated.
The problem is that reverseGeocodeLocation executes asynchronously, and you are not waiting for the calls to complete before logging the size of your output array. You might have better luck with something like:
for(CLLocation *location in locationOutputArray)
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
{
if(placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
NSString *address = [NSString stringWithFormat:#"%# %#,%# %#", [topResult subThoroughfare],[topResult thoroughfare],[topResult locality], [topResult administrativeArea]];
[addressOutputArray addObject:address];
NSLog(#"%#",address);
NSLog(#"Address output array count is now: %d", [addressOutputArray count]);
}
}];
[geocoder release];
}
In any case, you are doing everything correctly with your block in terms of how you are setting it up and using it to modify the state of your addressOutputArray ivar. The only problem is that you were not waiting until all your blocks had finished executing before checking the result.
Related
My question is, why are poiCoordinate's latitude and longitude properties coming out 0, 0 when addressTF.text has a very sensible address string, for example "1 Infinite Loop, Cupertino, CA 95014"?
//HomeViewController.m
#implementation HomeViewController
CLLocationCoordinate2D poiCoordinate;
-(void)performStringGeocode
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:_addressTF.text completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error)
{
NSLog(#"Geocode failed with error: %#", error);
return;
}
CLPlacemark *placemark = [placemarks firstObject]; //Line A
poiCoordinate = placemark.location.coordinate; //Line B
}];
}
I have 60 address and I want to add the pin for every address. I want to use google maps and not Apple maps. I have a loop outside, and calling this method for 100 elements.
And some times I got this error: *** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array
And the error is not regular, I mean the error does not corresponds to an exact address. Sometimes I got 20 errors, sometimes 15,...
Does anyone know how to resolve it?
thank you
- (CLLocationCoordinate2D) getLocationFromAddress:(NSString*) address
{
NSError *error = nil;
NSString *lookUpString;
NSDictionary *jsonDict;
NSData *jsonResponse;
NSArray *locationArray;
lookUpString = [[NSString alloc] initWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", address];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
jsonResponse = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:lookUpString]];
jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
locationArray = [[NSArray alloc] init];
locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
#try {
locationArray = [locationArray objectAtIndex:0];
NSLog(#" LOADING, %d, %d, %d", [locationArray count], [jsonDict count], [jsonResponse length]);
}
#catch (NSException *exception) {
NSLog(#"ERROR LOADING, %d, %d, %d", [locationArray count], [jsonDict count], [jsonResponse length]);
}
#finally {
}
NSString *latitudeString = [[NSString alloc] init];
latitudeString = [locationArray valueForKey:#"lat"];
NSString *longitudeString = [[NSString alloc] init];
longitudeString = [locationArray valueForKey:#"lng"];
NSString *statusString = [[NSString alloc] init];
statusString = [jsonDict valueForKey:#"status"];
double latitude = 0.0;
double longitude = 0.0;
if ([statusString isEqualToString:#"OK"])
{
latitude = [latitudeString doubleValue];
longitude = [longitudeString doubleValue];
}
else
NSLog(#"Something went wrong, couldn't find address");
_location.longitude = longitude;
_location.latitude = latitude;
return _location;
}
How can I manage calling an asynchronous block in a loop?
My code to be called n-times:
- (void) convertToCountries:(NSString*)time longitude:(NSString*)lon latitude:(NSString*)lat {
CLLocation *myLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
[geocoder reverseGeocodeLocation:myLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
if(placemarks && placemarks.count > 0)
{
//do something
CLPlacemark *topResult = [placemarks objectAtIndex:0];
NSString *addressTxt = [NSString stringWithFormat:#"%#, %# %#,%# %#", [topResult country],
[topResult subThoroughfare],[topResult thoroughfare],
[topResult locality], [topResult administrativeArea]];
NSLog(#"%#",addressTxt);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
[DataOperations saveRecord:[topResult country] time:time];
}
}];
}
I need to collect output data from these calls.
Any help will appreciated.
Give your object a property, BOOL dunloadin.
Then, in the completion block, set self.dunloadin to YES.
Finally, your loop should look something like this:
for (int i=0; i<10; i++)
{
self.dunloadin = NO;
[self convertToCountries:…];
while (!self.dunloadin)
{
[[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
However, you might want to consider designing your app differently so that kludges like this aren't required.
I'm using AFNetworking with AFHTTPRequestOperation to pull XML data from a webservice. This is working fine and im getting the data I need but I need to split this data into objects and initialize a NSMutableArray with this data. This is working in the completion block, but just before I return the array in my method the data is gone? How do I do this?
Here is some of my code:
NSMutableArray *result = [[NSMutableArray alloc] init];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* response = [operation responseString];
NSData* xmlData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSError *xmlError;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&xmlError];
NSArray *allElements = [doc.rootElement elementsForName:#"Misc"];
for (GDataXMLElement *current in allElements)
{
NSString *titel;
NSString *tekst;
NSArray *titels = [current elementsForName:#"Titel"];
if(titels.count > 0)
{
GDataXMLElement *firstTitel = (GDataXMLElement *) [titels objectAtIndex:0];
titel = firstTitel.stringValue;
} else continue;
NSArray *teksts = [current elementsForName:#"Tekst"];
if(teksts.count > 0)
{
GDataXMLElement *firstTekst = (GDataXMLElement *) [teksts objectAtIndex:0];
tekst = firstTekst.stringValue;
} else continue;
HVMGUniversalItem *item = [[HVMGUniversalItem alloc] initWithTitel:titel AndTekst:tekst];
[result addObject:item];
}
NSLog(#"%i", result.count);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [operation error]);
}];
[operation start];
NSLog(#"%i", result.count);
return result;
What am I doing wrong? Why isn't the data present in the array when returning?
Why isn't the data present in the array when returning?
Because AFNetworking use an async pattern. So the return code will be performed before the operation will be completed.
You need to use a different approach or follow Can AFNetworking return data synchronously (inside a block)?. The latter is discouraged.
A solution could be to:
-> Create a NSOperationQueue within your class that will include your operation. Create it as a property for your class like.
#property (nonatomic, strong, readonly) NSOperationQueue* downloadQueue;
- (NSOperationQueue*)downloadQueue
{
if(downloadQueue) return downloadQueue;
downloadQueue = // alloc init here
}
-> Create a property for your array (synthesize also it)
#property (nonatomic, strong) NSMutableArray* result;
-> Wrap your code within a specific method like doOperation.
self.result = [[NSMutableArray alloc] init];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
__weak YourClass* selfBlock = self;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* response = [operation responseString];
NSData* xmlData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSError *xmlError;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&xmlError];
NSArray *allElements = [doc.rootElement elementsForName:#"Misc"];
for (GDataXMLElement *current in allElements)
{
NSString *titel;
NSString *tekst;
NSArray *titels = [current elementsForName:#"Titel"];
if(titels.count > 0)
{
GDataXMLElement *firstTitel = (GDataXMLElement *) [titels objectAtIndex:0];
titel = firstTitel.stringValue;
} else continue;
NSArray *teksts = [current elementsForName:#"Tekst"];
if(teksts.count > 0)
{
GDataXMLElement *firstTekst = (GDataXMLElement *) [teksts objectAtIndex:0];
tekst = firstTekst.stringValue;
} else continue;
HVMGUniversalItem *item = [[HVMGUniversalItem alloc] initWithTitel:titel AndTekst:tekst];
[selfBlock.result addObject:item];
}
NSLog(#"%i", result.count);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [operation error]);
}];
[downloadQueue addOperation:operation];
-> if you need to notify that result has object send a notification, use the delegate pattern, etc...
Hope that helps.
How can I extract a CLRegion or CLLocationCoordinate2D or latitude/longitude points based on a correctly written country name? Would CLGeocoder work like this:
CLGeocoder *geoCode = [[CLGeocoder alloc] init];
[geoCode geocodeAddressString:#"Singapore" completionHandler:^(NSArray *placemarks, NSError *error) {
if (!error) {
CLPlacemark *place = [placemarks objectAtIndex:0];
NSLog(#"%i,%i", place.//what would i put here);
}
}];
What variable does a CLPlacemark hold that tells the address?
Never mind figured it out:
CLGeocoder *geoCode = [[CLGeocoder alloc] init];
[geoCode geocodeAddressString:#"Singapore" completionHandler:^(NSArray *placemarks, NSError *error) {
if (!error) {
CLPlacemark *place = [placemarks objectAtIndex:0];
CLLocation *location = place.location;
CLLocationCoordinate2D coord = location.coordinate;
NSLog(#"%g is latitude and %g is longtitude", coord.latitude, coord.longitude);
}
}];