Finish task before app did enter background

Discussion in 'iOS Programming' started by donaghy, Feb 24, 2011.

  1. donaghy macrumors member

    Joined:
    Aug 6, 2009
    #1
    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.
     
  2. firewood macrumors 604

    Joined:
    Jul 29, 2003
    Location:
    Silicon Valley
    #2
    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.
     
  3. donaghy thread starter macrumors member

    Joined:
    Aug 6, 2009
    #3
    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?
     
  4. donaghy thread starter macrumors member

    Joined:
    Aug 6, 2009
    #4
    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.
     

Share This Page