应用关闭时发送HTTP请求

时间:2014-04-29 22:57:45

标签: ios post nsurlconnection

所以当我的应用关闭时,我正在尝试做一个简单的POST请求。

我试过[NSURLConnection sendAsynchronousRequest]
并使用[NSURLConnection sendSynchronousRequest]执行dispatch_async。我想要的唯一实际工作就是在主线程上执行同步请求,但是它会滞后,特别是如果服务器响应缓慢。

这两种工作,除了他们在应用再次打开时发送实际请求,而不是在关闭时。我目前正在applicationDidEnterBackground执行此操作,但我也尝试了applicationWillResignActive

我也在应用Application does not run in background中设置了info.plist。没有变化。

我可以在应用程序打开时执行所有操作。但是如果我在关闭应用程序时能够实现它,那么代码会更好。

有可能吗?

1 个答案:

答案 0 :(得分:1)

来自applicationDidEnterBackground -

的文档
  

这可能是你开始的任何后台任务   applicationDidEnterBackground:直到该方法之后才会运行   退出,您应该在之前请求额外的后台执行时间   开始那些任务。换句话说,先打电话   beginBackgroundTaskWithExpirationHandler:然后在a上运行任务   调度队列或辅助线程。

因此,您正在请求异步操作,但此任务将在applicationDidEnterBackground返回之前不执行,并且一旦此方法返回您的应用程序将不再处于活动状态。当应用程序返回到前台时,任务就坐在那里并运行。

iOS编程指南提供有关executing a task when your app moves to the background

的建议

你需要像 -

这样的东西
- (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;
    });
}
相关问题