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])
case _ where code >= 300 && code < 400:
self.fetchedPages.updateValue(pageData, forKey: pageNumber)
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.