0

为了下载一堆 Twitter 时间线,我TWRequest在一个循环中创建了对象并将它们放入NSOperationQueue

twitterRequestQueue = [[NSOperationQueue alloc] init];

// Get a reference to a Twitter account

NSArray *screenNames = @[@"gruber", @"kottke", @"ev", @"brad", @"borkware", @"jack", @"greatdismal", @"wilshipley"];
NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json"];

for (NSString *screenName in screenNames) {
    NSDictionary *parameters = @{@"screen_name" : screenName, @"count" : @"200" };
    TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:parameters requestMethod:TWRequestMethodGET];
    [request setAccount:account];

    // Make an operation using the Twitter request
    NSBlockOperation *twitterOperation = [NSBlockOperation blockOperationWithBlock:^{
        [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
            // Do stuff with the responseData
        }];
    }];

    // Put the requests into an operation queue
    [twitterRequestQueue addOperation:twitterOperation];
}

为了确定何时下载了所有时间线,我首先尝试使用 KVO on twitterRequestQueue'soperationCount。在所有 Twitter 请求之后,我还尝试向队列添加依赖操作。这两个都失败了,因为 Twitter 请求几乎立即返回,并在调用完成块之前从操作队列中删除。

相反,我将我的请求手动存储在一个可变数组中,[self requestCompleted:request];在 Twitter 完成块的末尾调用一个自定义方法,并在每个完成时手动从我的可变数组中删除请求:

- (void)requestCompleted:(TWRequest *)request
{
    NSDictionary *parameters = [request parameters];
    NSString *screenName = [parameters valueForKey:@"screen_name"];
    NSLog(@"Request completed: %@", screenName);

    [requestsInProgress removeObject:request];
    if ([requestsInProgress count] == 0) {
        NSLog(@"All requests finished");
    }
}

我可以使它工作的另一种方法是signedURLRequest从 Twitter 请求中获取并使用sendSynchronousRequest:returningResponse:error:.

这是我的问题:

  • 使用 anNSOperationQueue下载这样的 Twitter 请求有什么意义吗?
  • 有没有更好的技术来下载多个 Twitter 请求?
  • 我可以改进为此使用操作队列的方式吗?
4

1 回答 1

0

Just use SLRequest and blocks. What do you want to achieve?

See for example https://github.com/ArchieGoodwin/NWTwitterHelper

于 2013-05-14T12:33:52.147 回答