Frage

I am trying to use AFJSONRequestOperation to pull one peace of data from a JSON feed.

The following code pulls the url just fine, and when stringURL is printed, it prints the correct url. However, I have tried a few different ways of assigning the url to a new variable, outside the scope of the block. Whether I try to assign the resulting url to another global NSURL (making sure to use __block) or try to add it to an array it seems to not update in time to print out in NSLog. I am suspecting this is because the operation has not finished. How do I make sure that the operation has finished before I call NSLog([streamUrls objectAtIndex:0]);?

Here is the code I am using.

    NSURL *url = [contentUrls objectAtIndex:indexPath.row];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSONSound) {

    NSString *stringURL = [NSString stringWithFormat:@"%@",
                           JSONSound[@"stream_url"], nil];

    NSURL *streamURL = [NSURL URLWithString:stringURL];
    NSLog(stringURL);
    [streamUrls addObject:streamURL];
    [self.collectionView reloadData];
} failure:nil];
[operation start];

NSLog([streamUrls objectAtIndex:0]);

EDIT: [self.collectionView reloadData]; this line does not seem to affect the situation.

War es hilfreich?

Lösung

To make sure the operation has finished before making any call to code, you can make use the success block of the AFJSONRequestOperation, which is what you have been doing when you adding the objects to the streamUrls:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSONSound) {
    NSString *stringURL = [NSString stringWithFormat:@"%@",
                       JSONSound[@"stream_url"], nil];

    NSURL *streamURL = [NSURL URLWithString:stringURL];
    NSLog(stringURL);
    [streamUrls addObject:streamURL];
    [self.collectionView reloadData];
    NSLog([streamUrls objectAtIndex:0]);
} failure:nil];

The reloadData does not affect the data source. It is just refreshing the collection view displayed based on the data source (whether the data source is updated or not).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top