Вопрос

So I am trying to do a simple POST request when my app closes down.

I've tried [NSURLConnection sendAsynchronousRequest]
and doing [NSURLConnection sendSynchronousRequest] with dispatch_async. The only thing that actually works as I want is to do the synchronous request on the main thread, but then it lags, especially if the server is slow to respond.

Both kind of work, except they send the actual request when the app opens again, instead of when it closes. I am currently doing this in applicationDidEnterBackground but I've tried applicationWillResignActive also.

I have set the Application does not run in background in the apps info.plist also. No change.

I could do all things when the app opens. But the code will be nicer if I can achieve it when closing the application.

Is it possible?

Это было полезно?

Решение

From the documentation for applicationDidEnterBackground -

it's likely any background tasks you start in applicationDidEnterBackground: will not run until after that method exits, you should request additional background execution time before starting those tasks. In other words, first call beginBackgroundTaskWithExpirationHandler: and then run the task on a dispatch queue or secondary thread.

So, you are requesting an asynchronous operation, but this task won't execute before applicationDidEnterBackground returns, and once this method returns your application will no longer be active. The tasks are sitting there and run once your app returns to the foreground.

The iOS programming guide provides advice on executing a task when your app moves to the background

You will need something like -

- (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

        [NSURLConnection sendSynchronousEvent....];
        // TODO process results..

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top