I am having an issue where using a background urlsession, and my willPerformHTTPRedirection
doesn't get called:
private class BackgroundCachingDelegate: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate
{
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest?
{
//... Never gets called
}
}
I call it like this:
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()
}
The code works if I take the redirected URL directly and try using that.
I also know for sure the server is performing a redirect:
Any ideas?
Update
Also maybe to mention, I do get a response of 0 bytes back with the redirected url as the response url. I could have an edge case based on the above and call the new redirected url, but I'd prefer the correct approach if that's not it.
Background url sessions are handled by the operating system, not your app process. Therefore there are some limitations on how they operate.
In particular, redirections are always followed
- Redirects are always followed. As a result, even if you have implemented
urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)
, it is not called.
So, the delegate method not being called is the expected behaviour. You need to investigate why you are not getting any data from the redirection.