Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 466
PopKernel Avatar asked Mar 12 '23 02:03

PopKernel


1 Answers

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.

like image 85
jatoben Avatar answered Mar 21 '23 02:03

jatoben