菜鸟教程小白 发表于 2022-12-11 22:39:30

ios - 当应用程序发送到后台模式时如何继续接收数据?


                                            <p><p>在 iOS12 中,如果网络请求不是 <code>URLSessionDownloadTask</code> 并设置后台 session ,则苹果开始取消网络请求。 </p>

<p>但根据苹果官网:</p>

<blockquote>
<p>You don’t have to do all background network activity with background
sessions... Apps that declare appropriate
background modes can use default URL sessions and data tasks, just as
if they were in the foreground</p>
</blockquote>

<p>我正在使用自定义播放器流式传输媒体文件,应用程序启用了 <code>Audio</code> 和 <code>Background Fetch</code> 模式。 <code>URLSessionDataTask</code> 在应用程序进入后台状态后立即在前台初始化任务被取消。 </p>

<p>我知道 AVPlayer 可以在后台流式传输,但不能使用 AVPlayer。</p>

<p>我知道我可以使用 <code>URLSessionDownloadTask</code> 设置 session ,该 session 将在单独的进程中下载数据并返回文件路径,由于流式传输要求,这不是一个选项。 </p>

<p>我知道我可以使用 <code>UIApplication.shared.beginBackgroundTask</code> 请求额外的后台执行时间,但这不是可接受的解决方案,因为如果 <code>backgroundTimeRemaining</code> 在流完成应用程序之前过期被杀了。</p>

<p>当应用程序处于后台模式时,有什么方法可以继续接收数据? </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>确保您的后台 session 具有 <a href="https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1409517-shoulduseextendedbackgroundidlem" rel="noreferrer noopener nofollow"><code>shouldUseExtendedBackgroundIdleMode</code></a>启用。如果不这样做,当应用程序从前台执行转换到后台执行时, session 将停止数据任务。或者,就像 <a href="https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_in_the_background" rel="noreferrer noopener nofollow">Downloading Files in the Background</a>文件说,你可以使用<a href="https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1411560-default" rel="noreferrer noopener nofollow"><code>default</code></a> session 配置也没有表现出这种行为。</p>

<hr/>

<p>FWIW,使用 <code>AVPlayer</code> 时,除了启用背景音频功能...</p>

<p> <a href="/image/KPTvT.png" rel="noreferrer noopener nofollow"><img src="/image/KPTvT.png" alt="enter image description here"/></a> </p>

<p>...您可能还必须告诉共享 Audio Session 实例它处于事件状态:</p>

<pre><code>try AVAudioSession.sharedInstance().setCategory(.playback)
try AVAudioSession.sharedInstance().setActive(true)
</code></pre>

<p>我不能说你的“自定义播放器”需要什么,但对我来说,我必须同时做这两个来保持应用程序在后台运行,使用 <code>AVPlayer</code> 播放音频。</code> p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 当应用程序发送到后台模式时如何继续接收数据?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/55401888/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/55401888/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 当应用程序发送到后台模式时如何继续接收数据?