使用api获取错误消息

时间:2018-04-09 12:12:34

标签: json swift xcode api

我有一个api,我在其中发布一些信息并获得回复并发布...

代码:

func makePostCall() {
    let todosEndpoint: String = "my link"
    guard let todosURL = URL(string: todosEndpoint) else {
        print("Error: cannot create URL")
        return
    }
    var todosUrlRequest = URLRequest(url: todosURL)
    todosUrlRequest.httpMethod = "POST"
    let newTodo: [String: Any] = ["name": "Lama", "email": "lama@me.com", "password": "1234"]
    let jsonTodo: Data
    do {
        jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
        todosUrlRequest.httpBody = jsonTodo
    } catch {
        print("Error: cannot create JSON from todo")
        return
    }
    let session = URLSession.shared
    let task = session.dataTask(with: todosUrlRequest) {
        (data, response, error) in
        guard error == nil else {
            print("error calling POST on /public/api/register_customer")
            print(error!)
            return
        }
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }
        // parse the result as JSON, since that's what the API provides
        do {
            guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData,
            options: []) as? [String: Any] else {
                    print("Could not get JSON from responseData as dictionary")
                        return
            }
            print("The todo is: " + receivedTodo.description)
            guard let status = receivedTodo["success"] as? Int else {
                print("Could not get status from JSON")
                return
            }
            if status == 0{
                print("The status is: 0")
                guard let message = receivedTodo["message"] as? String else {
                    print("Could not get message from JSON")
                    return
                }
                print("The error is:" + message)
            }
            else {
                print("Success!")
            }
        } catch  {
            print("error parsing response from POST on /public/api/register_customer")
            return
        }
    }
    task.resume()
}

我得到了这个结果:

 The todo is: ["message": {
 email =     (
 "The email field is required."
 );
 name =     (
 "The name field is required."
 );
 password =     (
 "The password field is required."
 );
 }, "success": 0]
 The status is: 0
 Could not get message from JSON

当我没有将这些字段留空并且未检索到该消息时..

消息是一个数组,我想显示所有这些

我希望它能正确发布......

有什么问题?

1 个答案:

答案 0 :(得分:0)

我解决了我的问题..但是我发布它以防这对某人有帮助。

正如@vadian所说(谢谢)我需要告诉服务器我发送了JSON,所以我添加了这一行:

todosUrlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

这解决了它!