【问题标题】:Getting nil Array of Follower back when performing asynchronous request执行异步请求时返回nil Array of Follower
【发布时间】:2012-01-12 08:17:28
【问题描述】:

我正在使用 Twitter iOS 5 框架做一个 Twitter 应用程序,它运行良好。 我正在设备上搜索所有可用的 TwitterAccounts 并将它们加载到 tableview 中以显示它们。如果用户触摸一个帐户,则会加载下一个视图,并通过 REST API 请求所有关注者并加载到数组中以使用 REST API 解析每个名称和照片。问题是,请求不是异步的,我首先得到一个 nil 数组,然后得到 API 的响应。

requestMethod如下:

__block NSArray *responseArray;

NSURL *tweetURL = [NSURL URLWithString:@"https://api.twitter.com/1/followers/ids.json"];

NSString *username = [[[self getAvailableTwitterAccounts] objectAtIndex:user] username];

NSMutableDictionary *parameters = [[NSMutableDictionary alloc] 
                                   initWithObjects:[NSArray arrayWithObjects:@"-1", username, @"1", nil]
                                   forKeys:[NSArray arrayWithObjects:@"cursor", @"username", @"stringify_ids" ,nil]];

//Build request
TWRequest *getFollowerRequest = [[TWRequest alloc] initWithURL:tweetURL 
                                                    parameters:parameters
                                                    requestMethod:TWRequestMethodGET];

[getFollowerRequest setAccount:[[self getAvailableTwitterAccounts] objectAtIndex:user]];
[getFollowerRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){
    dispatch_async(dispatch_get_main_queue(), ^{
        NSError *jsonParsingError = nil;
        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
        responseArray = [response objectForKey:@"ids"];
        NSLog(@"responseArray %@ for user: %@",responseArray,username);
  });  
}];

return responseArray;
}

以及加载过程:

- (void)viewWillAppear:(BOOL)animated
{   

followerIDArray = [[NSArray alloc] initWithArray:[[NBNTwitterConnect sharedTwitterConnect] getFollowerIDsForUser:userID]];
[super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self initDisplayArray];
}

-(void)initDisplayArray{

NSLog(@"followerIDArray: %@",followerIDArray);

[self performSelectorOnMainThread:@selector(arrayDidFinishedLoading:) withObject:nil waitUntilDone:NO];
}

-(void)arrayDidFinishedLoading:(NSArray *)array{

[self.tableView reloadData];
}

和输出:

followerIDArray: (
)
2011-12-03 21:43:33.305 NBNTwitterChat[1858:10403] responseArray (
3840,
14064174,
281136865,
224987906
) for user:xyz 

任何人都可以帮助我吗?我搜索了整个网络,我需要使用 TWRequest 方法而不是 asihttprequest 或其他东西。

【问题讨论】:

    标签: iphone objective-c ipad frameworks twitter


    【解决方案1】:

    实际上我会说它异步的,这导致了问题。

    -[TWRequest performRequestWithHandler:] 是一个异步方法,会立即返回。你不能像你一样返回responseArray,因为在离开函数之前它不会被填充。

    您必须编写异步代码,或者您必须使用-[TWRequest signedURLRequest] 并执行同步请求。

    【讨论】:

      猜你喜欢
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多