Search code examples
objective-ccallbacknslog

Obj-C: Callback is not executing


Any idea why the callback is not executing? panoServie is initialized and everything. I put the NSLog messages there, and nothing happens.

- (CLLocationCoordinate2D) randomLatitudeLongitude
{
    CountryBBVal auBB = [[GGData SharedInstance] boundingBoxForCountry:Australia];
    //NSLog(@"BB: %f, %f, %f, %f", auBB.NELat, auBB.NELng, auBB.SWLat, auBB.SWLng);
    double ranLongitude = [self randomDoubleBetween: auBB.NELng and: auBB.SWLng]; // Boundix Box
    double ranLatitude = [self randomDoubleBetween: auBB.NELat and: auBB.SWLat];
    CLLocationCoordinate2D ranLatLng = CLLocationCoordinate2DMake(ranLatitude, ranLongitude);
    //NSLog(@"ranLatLng: [%f] [%f]", ranLatitude, ranLongitude);

    __block GMSPanorama *panPhoto = nil;
    [self.panoService requestPanoramaNearCoordinate:ranLatLng callback:^(GMSPanorama *panorama, NSError *error) {
            NSLog(@"panorama: %@ error: %@", panorama, error);

            panPhoto = panorama;
    }];

    if (!panPhoto) return [self randomLatitudeLongitude];


    return ranLatLng;
}

Solution

    1. - requestPanoramaNearCoordinate:callback: is asynchronous request. Its started and the code execution is not blocked. So the if (!panPhoto) return [self randomLatitudeLongitude]; is called immediately with panPhoto most probably being still nil, so the return statement is performed.

    2. Overall method idea does not seem right to me.

      • You should not have async block called in the getter-like method (which should return the result immediately). If you really want some method like this, you should define your own callback block for this method being called in the requestPanoramaNearCoordinate callback.
      • Calling return [self randomLatitudeLongitude] itself in the method is also not a good idea. It can cause infinite recursion. There should be at least some max recursion calls threshold