Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

donaghy

macrumors member
Original poster
Aug 6, 2009
49
0
Hi all. My application attempts to connect to a webservice and sending, receiving and parsing this information can be time consuming. This isn't a problem until the application is about to enter the background. The given 5 seconds to complete tasks isn't enough time so i would like to run it in the background until its finished. It would not take more than 60 seconds to complete. Does anyone know how i could do this? The task is running on the main thread so could I beginBackgroundTaskWithExpirationHandler and wait until the main thread is finished executing? Though I would assume the process of entering the background is on the main thread and i would have an infinite loop. Help appreciated.
 
You need to run the long network task in a background thread or async to begin with. Or else it will block the UI run loop and thus block the resign/suspend delegates and the OS will kill the app instead.
 
I have put the URLConnection work in an operation queue, when the application is about to move in the background i check if the operation is still running and wait until it finishes.

Code:
dispatch_async(dispatch_get_global_queue(0, 0), ^{ 
		NSLog(@"Starting background task with %f seconds remaining", app.backgroundTimeRemaining);
		
		while ([o isExecuting]) 
		{
		}
		
		NSLog(@"Finishing background task with %f seconds remaining", app.backgroundTimeRemaining);
		[app endBackgroundTask:taskId];
	});

However in the connection code i get an error at this line:

Code:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];

I'm not quite sure why it would fall at this line. Does the operation not run in it's own thread and current run loop is for the given thread?
 
I've read that NSRunloop is not thread safe and should not be run off the main thread. This being the case is there any alternative i can use? The code is quite simple:

Code:
while(running) 
	{
		if ([NSRunLoop currentRunLoop]) 
		{
			[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
		}
	}

I just need to wait for 1 second before checking if the URL connection is still running each time.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.