api给出错误的回应

时间:2019-09-20 11:08:37

标签: ios swift api

我在下面的代码中使用Alamofire编写了一个API管理器,效果很好。

 func apiGet(url:String,parameters:[String:Any] , completion: @escaping (_ data:[String:Any]? , _ error:Error?) -> Void)
    {
        if UIApplication.shared.isNetworkActivityIndicatorVisible == true
        {
            let manager = Alamofire.SessionManager.default
            manager.session.configuration.timeoutIntervalForRequest = 120

            manager.request(url, method:.get, parameters: parameters, encoding: URLEncoding.default, headers: headersintoApi()).responseJSON { (response:DataResponse<Any>) in
                UIApplication.shared.isNetworkActivityIndicatorVisible = false


                if response.result.isSuccess
                {
                    if let data = response.result.value as? [String:Any]
                    {
                        completion(data , nil)

                    }else{
                        Helper.Alertmessage(title: "Alert", message: (response.error?.localizedDescription)!, vc: nil)

                        completion(nil,response.error)
                    }
                }
                else
                {
                    Helper.Alertmessage(title: "Alert", message: (response.error?.localizedDescription)!, vc: nil)
                    completion(nil,response.error)
                    print("App error mesage is: \(String(describing: response.result.error))")
                }
            }

        }else{
            Helper.Alertmessage(title: "Alert!", message: "Please Check Internet Connection", vc: nil)

        }
    }

,但是在某些情况下,API响应以[[String:Any]]的形式出现,因此它崩溃了。有人对如何解决有建议吗?

1 个答案:

答案 0 :(得分:0)

将代码更改为以下代码,以处理需要响应的字典数组的情况

if let data = response.result.value as? [String:Any]
                    {
                        completion(data , nil)

                    }
else if let data = response.result.value as? [[String:Any]]
                    {
                        completion(data , nil)

                    }
else{
                        Helper.Alertmessage(title: "Alert", message: (response.error?.localizedDescription)!, vc: nil)

                        completion(nil,response.error)
                    } 

还要保留类型Any?的完成参数数据以便正确处理。