ios - 应用关闭时发送 HTTP 请求
<p><p>所以我尝试在我的应用关闭时发出一个简单的 POST 请求。</p>
<p>我试过 <code></code><br/>
并使用 <code>dispatch_async</code> 执行 <code></code>。唯一真正按我的意愿工作的是在主线程上执行同步请求,但它会滞后,尤其是在服务器响应缓慢的情况下。</p>
<p>这两种工作都有效,只是它们会在应用再次打开时发送实际请求,而不是在应用关闭时发送。我目前正在 <code>applicationDidEnterBackground</code> 中执行此操作,但我也尝试过 <code>applicationWillResignActive</code>。</p>
<p>我还在应用程序 <code>info.plist</code> 中设置了 <code>Application does not run in background</code>。没有变化。</p>
<p>当应用打开时,我可以做所有事情。但是如果我能在关闭应用程序的时候实现,代码会更好。</p>
<p>有可能吗?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>来自 <code>applicationDidEnterBackground</code> 的文档 - </p>
<blockquote>
<p>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.</p>
</blockquote>
<p>因此,您正在请求一个异步操作,但在 <code>applicationDidEnterBackground</code> 返回之前不会执行此任务,并且一旦此方法返回,您的应用程序将不再处于事件状态。一旦您的应用返回前台,这些任务就会坐在那里并运行。</p>
<p>iOS 编程指南提供有关 <a href="https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW28" rel="noreferrer noopener nofollow">executing a task when your app moves to the background</a> 的建议</p>
<p>你需要类似的东西 - </p>
<pre><code>- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
;
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
;
// TODO process results..
;
bgTask = UIBackgroundTaskInvalid;
});
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 应用关闭时发送 HTTP 请求,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/23376779/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/23376779/
</a>
</p>
页:
[1]