从异步代码块返回NSDictionary?

时间:2012-05-24 18:01:20

标签: objective-c ios5 twitter nsurlrequest

  

可能重复:
  returning UIImage from block

您好我正在尝试返回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]);
         }];
      }

Thnx提前!

1 个答案:

答案 0 :(得分: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. }];

{{1}}