【问题标题】:Asynchronous Twitter operations in an NSOperationQueueNSOperationQueue 中的异步 Twitter 操作
【发布时间】:2013-05-08 17:33:01
【问题描述】:

为了下载一堆 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];
}

为了确定所有时间线的下载时间,我首先尝试了using KVO on twitterRequestQueue's operationCount。在所有 Twitter 请求之后,我还尝试了 adding a dependant operation to the queue。这两个都失败了,因为 Twitter 请求几乎立即返回并在它们的完成块被调用之前从操作队列中删除。

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

- (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 请求?
  • 我可以为此改进使用操作队列的方式吗?

【问题讨论】:

  • 我认为您应该依赖并发操作,因为在非并发操作中,当 main 终止时,操作将从队列中删除。如果您愿意,我可以尝试为您提供一些提示。祝你有美好的一天。

标签: ios objective-c twitter nsoperationqueue twrequest


【解决方案1】:

只需使用 SLRequest 和块。你想达到什么目标?

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

【讨论】:

    猜你喜欢
    • 2015-01-31
    • 1970-01-01
    • 2012-12-23
    • 2023-03-16
    • 2014-04-25
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    相关资源
    最近更新 更多