Limit NSURLConnection data rate? (Bandwidth throttling)

只愿长相守 提交于 2019-12-19 10:25:06

问题


Is there a way to limit the bandwidth used by an NSURLConnection, or I'm forced to use CFNetwork methods?


回答1:


Yes, but it's not pretty (it works according to this mailing list post):

  • Start NSURLConnection on a background thread (you'll have to set up a run loop).
  • Sleep in -connection:didReceiveData:.
  • Forward your data to the main thread in a thread-safe fashion.

The third bulletpoint is a little tricky to get right if the delegate is a UIViewController, but something like this should work provided delegate is __weak or __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];
}

Calculating how long to sleep for is non-trivial because you may wish to account for TCP/IP overheads, but [data length]+100 may be about right.

If you have multiple connections and you want to throttle the combined bandwidth, put them all on the same background thread/run loop (see -performSelector:onThread:withObject:waitUntilDone:).

For the CFNetwork version, I'm guessing you've read this post on Cocoa with Love.



来源:https://stackoverflow.com/questions/13314144/limit-nsurlconnection-data-rate-bandwidth-throttling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!