有没有办法限制 NSURLConnection 使用的带宽,或者我被迫使用 CFNetwork 方法?
			
			2156 次
		
1 回答
            1        
        
		
是的,但它并不漂亮(它根据这个邮件列表帖子工作):
- 在后台线程上启动 NSURLConnection(你必须设置一个运行循环)。
- 睡在-connection:didReceiveData:。
- 以线程安全的方式将数据转发到主线程。
如果委托是 a ,则第三个要点有点棘手,但如果是or UIViewController,这样的事情应该可以工作:delegate__weak__unsafe_unretained
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  [NSThread sleepForTimeInterval:...];
  [self performSelectorOnMainThread:@selector(notifyDelegateDidReceiveData:) withObject:data waitUntilDone:NO];
}
-(void)notifyDelegateDidReceiveData:(NSData*)data
{
  assert([NSThread isMainThread]);
  [delegate myConnectionWrapper:self didReceiveData:data];
}
计算睡眠时间很重要,因为您可能希望考虑 TCP/IP 开销,但[data length]+100可能是正确的。
如果您有多个连接并且想要限制组合带宽,请将它们全部放在同一个后台线程/运行循环中(请参阅 参考资料-performSelector:onThread:withObject:waitUntilDone:)。
对于 CFNetwork 版本,我猜你已经阅读过这篇关于 Cocoa with Love 的文章。
于 2012-11-09T19:10:46.427   回答