【问题标题】:Why calls swiftHTTP the response handler if there is no connection?如果没有连接,为什么调用 swiftHTTP 响应处理程序?
【发布时间】:2018-06-14 14:43:20
【问题描述】:

我正在使用 swiftHTTP 向我的服务器请求,当我的互联网连接速度很慢时,它会转到响应部分!我在下面设置了示例代码:

HTTP.GET("myURL") { response in
  let myResponse = response.data // it comes here after the timeout
  if response.statusCode == 200 {
    //some code
  } else {
       do {
         let jsonError = try JSON(data: myResponse) // in this line it goes to catch because there is no data in myresponse
       } catch{
         //alert for not having connection
       }
}

如果没有响应,为什么会调用响应函数?
我的服务器也说,没有发送请求。

【问题讨论】:

    标签: ios swift httprequest


    【解决方案1】:

    它不会“去响应”,它会尝试按预期发出 HTTP 请求,无论成功或错误,它的完成处理程序都会被调用。

    返回的响应对象是一个对象,其中包含确定请求发生情况所需的所有信息。

    因此它将包含一个超时状态代码 (HTTP 408),可能是一条错误消息。如果它根本没有响应,您的应用程序将无法处理这些情况。

    例如,您的用户在应用程序中点击他们的个人资料图标,这会发送一个请求以获取用户个人资料,但它超时了。您是否希望用户坐着等待,看着空白的个人资料屏幕?捕获错误并优雅地处理它要好得多。在这种情况下,您可以向用户显示一条消息,告诉他们出了点问题并关闭空白的个人资料屏幕

    【讨论】:

    • 状态码也可以为零,表示实际上没有请求完成。
    【解决方案2】:

    如果没有连接或连接非常糟糕,您的响应处理程序也会从 swiftHTTP 调用。
    要解决此问题,请check if there is an internet connection 或检查数据是否为零:

    HTTP.GET("myURL") { response in
      let myResponse = response.data // it comes here after the timeout
      if response.statusCode == 200 || response.data == nil {
        //some code
      } else {
           do {
             let jsonError = try JSON(data: myResponse) // in this line it goes to catch because there is no data in myresponse
           } catch{
             //alert for not having connection
           }
    }
    

    这里的重要部分是检查response.data == nil

    【讨论】:

      猜你喜欢
      • 2013-06-16
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2012-05-05
      • 2014-04-22
      相关资源
      最近更新 更多