0

I have a NSURLConnection which carries out the task of uploading images for me. This is how I initialize and start this connection:

_connection = [[NSURLConnection alloc]
                initWithRequest:request
                       delegate:self 
                startImmediately:NO];

[_connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                        orMode:NSDefaultRunLoopMode]; 
[_connection start];

I actually call this method from somewhere else with dispatch_async on its own dispatch_queue. The problem is when an image is uploading and I start typing in my app with keyboard, sometimes, it freezes the application. After a bit of digging I came to understanding that the mainRunLoop is actually what handles input requests such as keyboard button press. I wanted to know if I get it right and this is what actually causing my problem which is freezing my app. Any help regarding this issue is much appreciated. Thank you in advance.

P.S: I tried running my connection on currentRunLoop but it doesnt work unless I manually start the currentRunLoop.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mepla
  • 438
  • 4
  • 16
  • 1
    Consider using `NSRunLoopCommonModes` instead of `NSDefaultRunLoopMode`, and it will ensure that it is still called while there is some prolonged UI related activity (e.g. scrolling a scroll view). – Rob Apr 20 '14 at 10:58
  • BTW, your code above is only needed if you're starting request from background queue. Otherwise just do `initWithRequest:delegate:`. I don't think your problem rests with the above code. Is this question related to your question (which was a crash, not a freeze)? And when you say "freeze" are you saying that UI freezes, or merely that your network activity stops? – Rob Apr 20 '14 at 21:25

1 Answers1

0

The asynchronous NSURLConnection are meant to run inside a runloop. So you have two choices: use the main thread/main runloop or spawn another thread and start a separate runloop there. In the later case, you'd need to use [NSRunLoop currentRunLoop] instead of [NSRunLoop mainRunLoop].

I recommend going for the main thread/main runloop. The asynchronous NSURLConnection is very efficient, it's no problem having a lot of them run on the main thread. You won't notice any performance problems unless you do very expensive stuff in the delegate methods.

So simply run your code on the main thread and everything should be fine.

DarkDust
  • 90,870
  • 19
  • 190
  • 224