PopKernel PopKernel - 6 months ago 15
Swift Question

NSURLSession 3xx redirects and completion handlers

I have a dataTask + completionHandler approach to downloading data from a web server. So far I have implemented this:

let task = session.dataTaskWithURL(url, completionHandler: {
(pageData,response,error) in
...
...
let code = urlHttpResponse.statusCode
switch code {
case 200:
self.fetchedPages.updateValue(pageData, forKey: pageNumber)
case 404:
self.fetchedPages.updateValue(nil, forKey: pageNumber) //No data exists for that page
default:
self.fetchedPages.updateValue(nil, forKey: pageNumber) //No gurantee data exists for that page
}
NSNotificationCenter.defaultCenter().postNotificationName("pageDataDownloaded", object: self, userInfo: ["numberForDownloadedPage":pageNumber])


What I'm wondering is what happens if statusCode is a 3xx error? Will pageData contain the data at the redirected location? In other words, should I add

case _ where code >= 300 && code < 400:
self.fetchedPages.updateValue(pageData, forKey: pageNumber)


Or will the handler get called again with pageData containing the value at the redirected location and a fresh 200 status code? Or is handling redirects properly something I can only do using a delegate?

Answer

If you don't have a delegate or the delegate doesn't implement URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:), HTTP redirects will be automatically followed. In that case, you won't see the 30x statuses in your handler.