1

I am using NSUrlConnection for making http requests. I want to avoid event driven code, so I am making use of NSRunloop in the following way:

NSURLRequest *request = [[NSURLRequest alloc]
                         initWithURL: [NSURL URLWithString:_urlString]
                         cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                         timeoutInterval: 10
                         ];

NSURLConnection *connection = [[NSURLConnection alloc]  initWithRequest:request delegate:self];

if(!connection) 
{
    DebugLog(@"Creating a connection has failed");
    [self setValidationRequestResult:false];
} 
else 
{
    NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop];
    [self.connection start];
    while (self.isConnectionComplete == NO) 
    {
        NSDate* dateLimit = [NSDate dateWithTimeIntervalSinceNow:0.05];
        [currentRunLoop runUntilDate:dateLimit];
    }

    //TODO: check release of NSUrlConnection
   }
}

// Now perform remaining tasks ........

Is it okay to NSRunLoop in way shown above or should we post notifications in "didFailWithError" and "connectionDidFinishLoading" to write logic after the http request is done?

Anna
  • 945
  • 1
  • 9
  • 13
  • What is your reasoning behind "avoiding" event driven code? NSURLConnection was designed to attach itself to a runloop and post callbacks when data is available. – Brandon A Feb 16 '12 at 03:11
  • I want to perform certain tasks after obtaining response from the http request. If I write event driven code, I have to use PostNotification after the NSUrlConnection task is done and this forces me to break the code that can be hard to understand. – Anna Feb 16 '12 at 04:21
  • Better question, why aren't you just using `+[NSURLConnection sendSynchronousRequest:returningResponse:error:]`? – MyztikJenz Feb 16 '12 at 05:22
  • Blocking any thread is a bad idea (which is what sendSynchronousRequest does). Making the operating system do so many context switches (assuming you put the request on a separate thread), especially on a single core device, is bad on many levels (battery life, overall application performance). – Brandon A Feb 16 '12 at 16:59

1 Answers1

1

While that approach may be technically correct, I would encourage you to ask why you want to do this.

NSURLConnection was designed to attach itself to a runloop so the runloop can continue and not tie up that thread.

What I've done in my applications is have a class dedicated to managing my networking code and have delegate callbacks or pass in blocks to handle completion. You mentioned using Notifications and that is also a good idea.

This is the nature of asynchronous networking code. It makes the code a bit more complicated, but your application will be better off.

Brandon A
  • 926
  • 7
  • 6