1

我编写 iPhone 应用程序。在这个应用程序中,我使用 Twitter 框架。在这个框架中,去同步中的回调函数在其他线程中。

在我的视图控制器中,

视图控制器.m

 [accountStore requestAccessToAccountsWithType:accountType
                        withCompletionHandler:^(BOOL granted, NSError *error) {
                            if (granted) {
                                if (account == nil) {
                                    NSArray *accountArray = [accountStore accountsWithAccountType:accountType];
                                    account = [accountArray objectAtIndex:2];
                                }

                                if (account != nil){
                                    NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/user_timeline.json"];
                                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                                    [params setObject:@"1" forKey:@"count"];

                                    TWRequest *request = [[TWRequest alloc] initWithURL:url
                                         parameters:params 
                                      requestMethod:TWRequestMethodGET];
                                    [request setAccount:account];
                                    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
                                        if (responseData) {
                                            //Throw response data to other Web API
                                            [self otherAPI:responseData];
                                            [[NSRunLoop currentRunLoop] run];
                                        }
                                    }];

                                }
                            }


                        }];

我在这个类中编写了这些方法。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

但我无法从其他 API 接收完整数据。我只能接收第一个数据。我认为进行多线程存在一些问题。因此,我想让我知道这段代码有什么问题。

4

1 回答 1

0

我想我看到了你的问题。-connection:didReceiveData:被多次调用,你需要建立一个包含整个消息的 NSMutableData 对象。

注意:这仅适用于每个实例一次下载一次。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.responseData = [[NSMutableData dataWithCapacity:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // self.responseData has all the data.
}
于 2012-07-03T04:56:53.543 回答