ios - 我如何在 Alamofire 中检查我的请求已发送?

标签 ios swift alamofire

使用 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如果响应具有 Not Acceptable 状态代码或 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响应的 header 与 Accept 匹配请求 header (如果提供的话)。

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 在 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 Usage .你可以更深入地了解一下。

关于ios - 我如何在 Alamofire 中检查我的请求已发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699634/

相关文章:

swift - 从 SKScene 继续并再次返回导致游戏到 "freeze"

swift - 401 alamofire 获取带有 header 的请求

swift - 无法从函数内更改全局变量

ios - alamofire 没有准备正确的 url

iOS : Send Multiple Apple Push Notification

ios - 相机应用程序//我需要什么代码来显示刚刚拍摄的照片?

macos - 在 Mac OS X 中访问扫描仪

swift - 如何在 swift 中使用带有开关的 AS 来获取类类型

IOS7 : uisearchdisplaycontroller always show scope bar

iphone - 使用 Storyboard iOS 5 的 RSS Feed iPhone