0

AFNetworking 默认的 runLoopModes 是 NSRunLoopCommonModes。我想使用 NSDefaultRunLoopMode,并设置它

 operation.runLoopModes = [NSSet setWithObject:NSDefaultRunLoopMode];

但它不起作用。当我滚动滚动视图时,下载任务仍在运行。任何人都可以帮助我吗?谢谢。

4

2 回答 2

1

所以我们开始了,替代解决方案,没有硬编码注入。假设您正在使用 UIImageView+AFNetworking 扩展:

// user began scrolling
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [[UIImageView af_sharedImageRequestOperationQueue] setSuspended:YES];
}

// user released finger and scrolling animation is finished
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[UIImageView af_sharedImageRequestOperationQueue] setSuspended:NO];
}

另请查看 Foursquare 的解决方案,它依赖于相同的技术。

于 2012-09-03T12:38:04.463 回答
0

最近我在 UITableView 中实现图像延迟加载时遇到了类似的问题。用户滚动在这里应该有更高的优先级。

您的方向是正确的,问题在于运行循环模式。使用 UIImageView+AFNetworking 扩展,图像使用 AFURLConnectionOperation 加载,它在单独的网络线程上工作(参见实现),因此 NSURLConnections 不在主线程上运行。

要在 UITrackingRunLoopMode 处于活动状态时停止任务,您需要以某种方式在主线程上移动网络代码。

可能的解决方案:

  1. 为您的请求操作设置默认运行循环模式。

    AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
    [requestOperation setRunLoopModes:[NSSet setWithObject:NSDefaultRunLoopMode]];
    
  2. 将连接放在主线程上(没关系,NSURLConnections 正在运行自己的线程):查找+ (NSThread *)networkRequestThread并使其返回[NSThread mainThread]。这可能不适合其他情况,小心锁。

我仍然不确定 AFNetworking 为什么要创建它的单独网络线程。在后台处理传入的数据?如果有人猜到了,请回复。

另请参阅问题。

于 2012-09-02T20:55:58.287 回答