gpt4 book ai didi

ios - 应用程序关闭时发送 HTTP 请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:36 33 4
gpt4 key购买 nike

因此,当我的应用关闭时,我尝试执行一个简单的 POST 请求。

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

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

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

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

这可能吗?

最佳答案

来自 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)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;
});
}

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com