限制NSURLConnection数据速率? (带宽限制)

有没有办法限制NSURLConnection使用的带宽,或者我被迫使用CFNetwork方法?

是的,但它不是很漂亮(根据这个邮件列表的post ):

  • 在后台线程上启动NSURLConnection(你将不得不build立一个运行循环)。
  • 睡眠中的-connection:didReceiveData:
  • 以线程安全的方式将数据转发到主线程。

如果代理是一个UIViewController ,第三个bulletpoint是有点棘手的,但是像这样的东西应该工作提供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爱的这篇文章 。

Interesting Posts