Search code examples
iosjsonperformselector

performselector won't execute


I'm receiving a json response from the foursquare api. Once I check to see if I have data I attempt to execute a the "loadNearestCoffeeShops" method. During debugging I notice the app simply stops when it gets to [self performSelector:@selector(loadNearestCoffeeShops:) withObject:data afterDelay:0];

Here's my code ... Any suggestions?

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation   *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"updated to location");
    //Optional: turn off location services once we've gotten a good location
    [manager stopUpdatingLocation];

    NSURLSession *session = [NSURLSession sharedSession];
    NSString *myURL = [NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?client_id=%@&client_secret=%@&v=%@&ll=%f,%f&venue=%@", clientID, clientSecret, version, newLocation.coordinate.latitude, newLocation.coordinate.longitude,venue_type];
    //NSLog(jsonURL);
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:myURL] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSMutableDictionary *allCoffeeShops= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", allCoffeeShops);
        if (data)
        {
            [self performSelector:@selector(loadNearestCoffeeShops:) withObject:data afterDelay:0];
        }
        else
        {
            NSLog(@"No Damn Data");
        }
    }];
    [dataTask resume];

Solution

  • Alternatively you could do something like this:

    if (data)
    {
        [self performSelectorInBackground:@selector(loadNearestCoffeeShops:) withObject:data];
    }
    ....
    

    Keeping in mind that if loading the nearest coffee shops require any UI related work you then have send that back to the main thread via:

    [self performSelectorOnMainThread:... withObject:... waitUntilDone:...]