我们可以在swift中获取HttpStatus Code错误描述吗?

时间:2017-03-13 09:19:19

标签: swift2 swift2.3

我在我的应用中使用Uber Api。当我尝试预订时会出现问题。我收到了httpStatus 400错误。根据他们的文档,这可能是由于各种因素造成的。 enter image description here

如何通过状态代码(始终为“400”)了解给定类型的哪种描述会导致它?。

我的代码现在:

 if let httpstatuscode = response as? NSHTTPURLResponse
        {
            if (error != nil)
            {
                print("Error : \(error?.localizedDescription)")
            }
            else if httpstatuscode.statusCode != 202 && httpstatuscode.statusCode != 409
            {

                print("Status Code\(httpstatuscode.statusCode)")

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    CommonViewController.alertViewUI("Alert", message: "Internal Server Error!")
                })

            }
            else if httpstatuscode.statusCode == 409
            {
               // self.getUberRideLive()
                print("Status Code\(httpstatuscode.statusCode)")
                CommonViewController.alertViewUI("Alert", message: "You are already on a ride!")



            }

1 个答案:

答案 0 :(得分:3)

您可以使用localizedString(forStatusCode:) method

中的HTTPURLResponse class

如果您想获取HTTP错误的描述,这是有效的,如果您想要从UBER错误中获取描述,您应该查看来自UBER操作的JSON响应。

然后,您的代码应该看起来像......

let message: String = HTTPURLResponse.localizedString(forStatusCode: httpstatuscode.statusCode)