OGeek|极客世界-中国程序员成长平台

标题: ios - 应用关闭时发送 HTTP 请求 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 21:52
标题: ios - 应用关闭时发送 HTTP 请求

所以我尝试在我的应用关闭时发出一个简单的 POST 请求。

我试过 [NSURLConnection sendAsynchronousRequest]
并使用 dispatch_async 执行 [NSURLConnection sendSynchronousRequest]。唯一真正按我的意愿工作的是在主线程上执行同步请求,但它会滞后,尤其是在服务器响应缓慢的情况下。

这两种工作都有效,只是它们会在应用再次打开时发送实际请求,而不是在应用关闭时发送。我目前正在 applicationDidEnterBackground 中执行此操作,但我也尝试过 applicationWillResignActive

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

当应用打开时,我可以做所有事情。但是如果我能在关闭应用程序的时候实现,代码会更好。

有可能吗?



Best Answer-推荐答案


来自 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.

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

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

你需要类似的东西 -

- (void)applicationDidEnterBackgroundUIApplication *)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;
    });
}

关于ios - 应用关闭时发送 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23376779/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4