lock screen interrupts NSURLConnection
Asked Answered
F

1

6

I'd like to know what's happening behind the scenes when the user locks and unlocks the iPad screen. I have an app that downloads files using NSURLConnection and the downloads fail with a SOAP error ("A server with the specified hostname could not be found"), but not when the user locks the screen, but when it unlocks it. Regardless of the fact when the error pops up, the download never finishes. Any ideas why and what could be done about it ?

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:300];

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

From what I can tell, when I hit the Home button I get:

applicationWillResignActive
applicationDidEnterBackground

and after I recall the app after three minutes I get:

applicationWillEnterForeground

and the download is either already finished or has progressed even in the background.

When I leave it in the background longer (5 minutes) it times out with an error.

When I lock the screen I get the same order of application states, but also an error message about the download disconnection.

Thank you!

Frostbitten answered 6/11, 2012 at 19:56 Comment(1)
I'm looking for an elegant solution to this problem too - preferrably one that doesn't involve cancelling the connection.Impediment
A
5

My guess is that your connection is getting disconnected because it's running when the app enters background, and you didn't have the correct implementations to keep it running. Maybe you should take a look at Apple's Background Execution and Multitasking documentation. It will show you how to leave your app running in the background up to about 10 minutes without being terminated. Look for the following sample code and learn how it might be able to solve your problem:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you.
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}
Amyl answered 7/11, 2012 at 4:13 Comment(3)
Thank you. This looks promising.Frostbitten
Why return immediately? If so, how will continue connection with internet?Hesson
@Amyl how to Use this Method? I need to use this bgTask in that part of my app I want to work in background?Ninnette

© 2022 - 2024 — McMap. All rights reserved.