13

I have a problem in that I am trying to background load a sound file while the user moves around a UIScrollView... The problem is that I am using NSURLRequest so I can load in the background, but even then it refuses to actually load until the UIScrollView has stopped scrolling. :(

Is there anything I can do about this?

Thanks!

jowie
  • 8,028
  • 8
  • 55
  • 94

2 Answers2

27

The NSURLRequest only manages the request, not the actual connection.

Touch events such as scrolling will place the run loop into NSEventTrackingRunLoopMode. By default, an NSURLConnection is scheduled to only execute in NSDefaultRunLoopMode. So while in NSEventTrackingRunLoopMode, NSDefaultRunLoopMode is blocked.

Good news is that you can schedule additional modes for an NSURLConnection, such as NSRunLoopCommonModes.

connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];
tidwall
  • 6,881
  • 2
  • 36
  • 47
  • Thanks for this... Saved me a huge headache! :-) what is the difference between NSEventTrackingRunLoopMode and NSRunLoopCommonModes? – jowie Nov 04 '10 at 14:09
  • 1
    AFAIK, a connection that is scheduled in NSRunLoopCommonModes will be monitored by all run loops. If it were scheduled in NSEventTrackingRunLoopMode, then it would only be monitored while there are touch events. http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/doc/uid/20000321-CJBJABGH – tidwall Nov 04 '10 at 17:41
1

I've figured out the hard way that if you call startImmediately:YES or ommit this parameter second line is completely useless. So be sure to follow the exact pattern provided by @tidwall.

Here's also a swift example:

self.connection = NSURLConnection(request: self.request, delegate: self, startImmediately:false)
self.connection?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
self.connection?.start()
hris.to
  • 6,235
  • 3
  • 46
  • 55