加载JSON时如何处理 [英] How do something when JSON is loaded

查看:100
本文介绍了加载JSON时如何处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JSON连接,加载JSON字符串时如何处理,如果没有,请期待完全加载。在这种情况下,加载后我想显示一条吐司消息。加载信息时通常会延迟几秒钟。

I have JSON connection, how do something when JSON String is loaded, and if not - expect for full loading. In this case after loading I want to show a toast message. Usually there is a delay of a couple of seconds when the information is loaded.

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}
        }

    }

}


推荐答案

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

The below is how you would use Alamofire to automatically validate the response. If the response comes back within the 200 range, you can run some code and if it comes back anything else it will fail and you can catch any errors there. You can also start and stop an activity indicator in the following code so that the user gets some notice that a background action is taking place.

//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

    }

}

这篇关于加载JSON时如何处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆