【发布时间】:2018-03-15 22:55:52
【问题描述】:
使用Alamofire,是否有可能在下载完整文件之前有一个处理头部响应的功能?
例如:
我们的应用在多个页面上使用相同的元素。这些元素是使用请求收集的。每个请求都有自己的哈希(md5 校验和)。我们在标头中发送此哈希,如果在缓存系统中识别出哈希,我想中止请求。
示例实现
APIManager.sharedManager.request(url, method: method, parameters: parameters)
.doSomethingHere {
//I want to read the headers here, before the data is fetched from the server.
//There needs to be an option here to cancel the request.
}
.responseJSON { response in
//If the request isn't cancel in the function above. The data should be here.
}
}
编辑:解决方案(Alamofire 实施 SWIFT 3)
APIManager.sharedManager.delegate.dataTaskDidReceiveResponse =
{(session:URLSession, dataTask:URLSessionDataTask, response:URLResponse) -> URLSession.ResponseDisposition in
if let httpResponse = response as? HTTPURLResponse {
//Do something with headers here. If you don't want to continue the request:
return URLSession.ResponseDisposition.cancel
}
return URLSession.ResponseDisposition.allow
}
APIManager.sharedManager.request(url, method: method, parameters: parameters)
.responseJSON { response in
//Response contains no data if it was canceled.
}
}
【问题讨论】:
-
你只能使用两个请求来实现你想要的。响应标头是响应本身的一部分,那么如何在获取响应之前检查标头?
-
嗨,大卫。我看到我的标题不正确。我想验证响应标头,然后决定是否要下载完整的响应正文。
-
是否应该可以在收到标头时中止请求?喜欢stackoverflow.com/questions/17390319/…
-
它是相关的,因为它使用了相同的技术。 iOS 正在执行 HTTP 请求(就像 PHP CURL 一样),我希望 alamofire 停止根据标头中的数据获取数据。
-
这正是我想要的,但是当标头包含一些信息时,我想用完整的主体“继续”流而不丢失连接/让服务器再次计算主体。
标签: ios swift request http-headers alamofire