【问题标题】:How do something when JSON is loaded加载 JSON 时如何做某事
【发布时间】:2017-08-30 18:19:20
【问题描述】:

我有 JSON 连接,当 JSON 字符串被加载时怎么办,如果没有 - 期望完全加载。在这种情况下,加载后我想显示一条 toast 消息。加载信息时通常会有几秒钟的延迟。

Alamofire.request("https://codewithchris.com/code/afsample.json").responseJSON{ response in

        if let value = response.result.value{

            let json = JSON(value) 
            \\ view.makeToast("JSONIsLoaded", duration: 2, position: bottomLayoutGuide, title: "title", image: UIImage (named: "logo.jpg"), style: style ) { (success: Bool) in}
        }

    }

}

【问题讨论】:

  • 搜索DispatchQueue.main.async
  • 问题令人困惑。加载后你想做什么?您是否要在加载时显示活动指示器?
  • @Martheli,从 json 中获取一些值并显示出来。只是想大致了解
  • @rmaddy,谢谢

标签: swift alamofire


【解决方案1】:

以下是使用 Alamofire 自动验证响应的方法。如果响应返回到 200 范围内,您可以运行一些代码,如果它返回任何其他内容,它将失败,您可以在那里捕获任何错误。您还可以在以下代码中启动和停止活动指示器,以便用户注意到正在发生后台操作。

//start activity indicator here

Alamofire.request("https://codewithchris.com/code/afsample.json").validate().responseJSON { response in

    switch response.result {

    case .success(let value):

          if let json = JSON(value) {
            // Do whatever you want with json
            //hide activity indicator here
           }
           else
            {
             //No data returned
            }

    case .failure(let error):
        print(error)
        //hide activity indicator here

    }

}

【讨论】:

    【解决方案2】:

    Alamofire 在后台请求。所以你也会在背景线程中得到响应。但是我们应该在主线程中刷新或更新 ui,因为会有延迟,或者可能在后台线程中找不到任何带有代码的 ui 更新。所以使用 DispatchQueue.main.async{ ui 更新代码 }

    【讨论】:

      猜你喜欢
      • 2013-09-09
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多