繁体   English   中英

NSOperationQueue中的异步Twitter操作

[英]Asynchronous Twitter operations in an NSOperationQueue

要下载大量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];
}

为了确定何时下载了所有时间表,我首先尝试twitterRequestQueueoperationCount上使用KVO 在所有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");
    }
}

我可以使其工作的另一种方法是从Twitter请求中获取signedURLRequest ,并使用sendSynchronousRequest:returningResponse:error:同步下载它。

这是我的问题:

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

只需使用SLRequest和块。 您想实现什么?

参见例如https://github.com/ArchieGoodwin/NWTwitterHelper

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM