我在使用后台 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。我可以根据上面的情况有一个边缘情况并调用新的重定向网址,但如果不是这样,我更喜欢正确的方法。