NSURLSession 3xx redirects and completion handlers

。_饼干妹妹 提交于 2019-12-14 01:26:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37620874/nsurlsession-3xx-redirects-and-completion-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!