1

可能重复:
从块返回 UIImage

嗨,我正在尝试返回 json twitter 数据的字典,以便我可以在我的应用程序中使用它。如何从异步块中调用它。我无法保存或返回任何想法?

  -(NSDictionary *)TweetFetcher
    {

    TWRequest *request = [[TWRequest alloc] initWithURL:
                          [NSURL URLWithString: @"http://search.twitter.com/search.json?
    q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"] parameters:nil 
    requestMethod:TWRequestMethodGET];


    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse 
    *urlResponse, 
    NSError *error)
     {
         if ([urlResponse statusCode] == 200) 
         {
             NSError *error;        
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData 
             options:0 error:&error];


             //resultsArray return an array [of dicitionaries<tweets>];
             NSArray* resultsArray = [dict objectForKey:@"results"]; 
             for (NSDictionary* internalDict in resultsArray)

                 NSLog([NSString stringWithFormat:@"%@", [internalDict 
             objectForKey:@"from_user_name"]]);
        ----> return dict; // i need this dictionary of json twitter data
         }
         else
             NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
         }];
      }

提前谢谢!

4

1 回答 1

3

我觉得我最近写了很多这样的异步代码。

- (void)tweetFetcherWithCompletion:(void(^)(NSDictionary *dict, NSError *error))completion
{
    NSURL *URL = [NSURL URLWithString:@"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"];
    TWRequest *request = [[TWRequest alloc] initWithURL:URL parameters:nil requestMethod:TWRequestMethodGET];

    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
        if ([urlResponse statusCode] == 200) {
            NSError *error;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];

            if (error) {
                completion(nil, error);
                return;
            }

            //resultsArray return an array [of dicitionaries<tweets>];
            NSArray* resultsArray = [dict objectForKey:@"results"]; 
            for (NSDictionary* internalDict in resultsArray)
                NSLog(@"%@", [internalDict objectForKey:@"from_user_name"]);

            completion(dict, nil);
        }
        else {
            NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
            completion(nil, error);
        }
    }];
}

因此,self.tweetDict = [self TweetFetcher];您可以这样称呼它,而不是调用 。

[self tweetFetcherWithCompletion:^(NSDictionary *dict, NSError *error) {
    if (error) {
        // Handle Error Somehow
    }

    self.tweetDict = dict;
    // Everything else you need to do with the dictionary.
}];
于 2012-05-24T19:10:22.387 回答