Swift 后台 downloadTask 不调用 willPerformHTTPRedirection

问题描述 投票:0回答:1

我在使用后台 urlsession 时遇到问题,并且我的

willPerformHTTPRedirection
没有被调用:

private class BackgroundCachingDelegate: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate
{
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest?
    {
        //... Never gets called
    }
}

我这样称呼它:

private func createNewBackgroundSession()
{
    let backgroundCachingConfiguration = URLSessionConfiguration.background(withIdentifier: OfflineCacheService.entityBackgroundSessionIdentifier)
    backgroundCachingConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData
    let backgroundCachingDelegate = BackgroundCachingDelegate(/*params*/)
    self.backgroundCachingSession = URLSession(configuration: backgroundCachingConfiguration, delegate: backgroundCachingDelegate, delegateQueue: nil)
}
    
private func startRequest(url: URL)
{
    if self.backgroundCachingSession == nil
    {
        self.createNewBackgroundSession()
    }
        
    var request = self.uiViewController.getURLRequest(method: "GET", url: url)
    request.cachePolicy = .reloadIgnoringCacheData
    self.backgroundCachingSession!.downloadTask(with: request).resume()
}

如果我直接获取重定向的 URL 并尝试使用它,代码就可以工作。

我也确定服务器正在执行重定向:

有什么想法吗?

更新

也许还要提一下,我确实收到了 0 字节的响应,其中重定向的 url 作为响应 url。我可以根据上面的情况有一个边缘情况并调用新的重定向网址,但如果不是这样,我更喜欢正确的方法。

ios swift background foreground nsurlsessiondownloadtask
1个回答
0
投票

后台 url 会话由操作系统处理,而不是您的应用程序进程。因此,它们的运作方式存在一些限制。

特别是,始终遵循重定向

因此,委托方法不被调用是预期的行为。您需要调查为什么没有从重定向中获取任何数据。

© www.soinside.com 2019 - 2024. All rights reserved.