使用 Alamofire 是否可以在发送请求时获取事件,无论是否收到响应?就像这个 URLSession 方法一样:
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
编辑:我的代码是向服务器发送一个 JSON:
Alamofire.request("http://...", method: HTTPMethod.post, parameters: params, encoding: JSONEncoding.default,
headers: [...]).responseJSON {
response in
if response.result.isSuccess {
print("result is Success")
} else {
print("result is Failure")
}
}
如果网络断开连接,我想处理什么,我想知道响应是否到达。
预先感谢您提供的任何帮助。
响应验证
默认情况下,Alamofire 将任何已完成的请求视为成功,而不管响应的内容如何。validate
如果响应具有不可接受的状态代码或 MIME 类型,则在响应处理程序之前调用会导致生成错误。
手动验证
Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
自动验证
自动验证200..<300
范围内的状态代码,并且Content-Type
响应的Accept
标头与请求的标头匹配(如果提供)。
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
统计指标
时间线 Alamofire 在 a 的整个生命周期中收集计时,Request
并创建一个Timeline
对象作为所有响应类型的属性公开。
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.timeline)
}
以上报告了以下Timeline
信息:
Latency
: 0.428 秒Request Duration
: 0.428 秒Serialization Duration
: 0.001 秒Total Duration
: 0.429 秒取自Alamofire 用法。你可以有更深入的了解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句