Domanda

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];
È stato utile?

Soluzione

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:...]

Altri suggerimenti

From the Apple Documentation

Special Considerations

This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

I believe NSURLSessions run in dispatch queues, so you'd have an issue using this method. A better choice would be either dispatch_async, or performSelectorOnMainThread:...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top