问题描述
我有一个dataTask + completeHandler方法,用于从Web服务器下载数据.到目前为止,我已经实现了:
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])
我想知道,如果statusCode是3xx错误,会发生什么?pageData会在重定向位置包含数据吗?换句话说,我应该添加
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)
还是会使用包含重定向位置的值和新的200状态代码的pageData再次调用处理程序?还是在正确处理重定向时,我只能使用委托来做某事?
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?
推荐答案
如果您没有委托,或者委托没有实现 URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)
,将自动遵循HTTP重定向.在这种情况下,您不会在处理程序中看到30倍的状态.
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.
这篇关于NSURLSession 3xx重定向和完成处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!