菜鸟教程小白 发表于 2022-12-11 17:24:41

iOS 网络 - HTTP 连接和在后台运行


                                            <p><p>我有一个应用程序可以让用户发送带有图像的消息。用户可能会点击发送,然后立即关闭手机或切换到另一个应用程序。</p>

<p>我们遇到了一个问题,即如果网络连接暂时不良,消息将无法发送。我们改用 <a href="https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSessionConfiguration_class/index.html#//apple_ref/occ/clm/NSURLSessionConfiguration/backgroundSessionConfigurationWithIdentifier:" rel="noreferrer noopener nofollow">NSURLSession backgroundConfigurationWithIdentifier</a>这样后台应用程序不会立即使正在运行的请求超时。我们切换到对我们所有的 api 请求使用它,认为如果应用在错误的时间关闭,每个请求都能够在后台继续运行不会有什么坏处。</p>

<p>快进几周,我们注意到所有请求似乎都很慢。使用wireshark我刚刚发现这个后台 session 似乎对每个请求都使用了一个新的http连接,这意味着它需要为每个请求设置一个TCP连接和新的TLS握手,这给我们应用程序中的每个请求增加了约500ms的延迟。这是一件大事,但我在任何地方都找不到这种行为,包括上面的链接或 Apple 的 <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW44" rel="noreferrer noopener nofollow">background transfer considerations</a> .</p>

<p>所以我的问题是,这种行为是预期的,还是我在某处做错了什么? NSURLSession 是否有一种简单的方法来发出 HTTP 请求,该请求将使用现有的 keep-alive 连接(如果有的话),但如果应用程序移到后台,则可以回退到 backgroundConfiguration?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>NSURLSession 是实现您的用例的推荐方式。您是否尝试过设置 <code>backgroundSessionConfig.discretionary = true</code></p>

<p> <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/#//apple_ref/occ/instp/NSURLSessionConfiguration/discretionary" rel="noreferrer noopener nofollow">iOS Reference</a> </p>

<blockquote>
<p>A Boolean value that determines whether background tasks can be
scheduled at the discretion of the system for optimal performance.</p>
</blockquote>

<p>如果这没有帮助,我建议提交 <a href="https://developer.apple.com/bug-reporting/" rel="noreferrer noopener nofollow">bug</a>使用 iOS。</p></p>
                                   
                                                <p style="font-size: 20px;">关于iOS 网络 - HTTP 连接和在后台运行,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39239139/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39239139/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iOS 网络 - HTTP 连接和在后台运行