首页 > 解决方案 > Swift 中的 HTTP 请求和 JSON 解析

问题描述

所以,我正在尝试在 XCode 中制作一个非常简单的 watchOS 应用程序。它由一个按钮、两个标签和两个标签之间的分隔符组成。它是一个数字助理应用程序,需要与 Dialogflow ( https://dialogflow.com ) 交互。

该按钮调用该presentTextInputController函数,我想将该结果用作对我的 Dialogflow 代理的查询。

我需要发出一个 HTTP 请求,在 JS 中它看起来更像这样:

{
url:"https://api.api.ai/v1/query",
method:"post",
body:JSON.stringify({query:"userInput",lang:"en-US",sessionID:"yaydevdiner"}),
headers:{
contentType:"application/json; charset=utf-8",
Authorization:"Bearer <auth_token>"
}
}

响应是一个 JSON 对象,我需要将jsonObject["result"]["speech"]值作为字符串访问才能使用Label.setText()

我尝试过的所有事情都给出了关于 Any 类型和其他此类事情的错误。print由于XCode 中没有显示输出,因此我也无法进行太多调试。

我必须提一下,我是 Swift 的极端初学者,而且我不擅长处理它们的类型、转换和解包之类的事情。

有人可以告诉我如何处理这个请求以及 JSON 的后续处理吗?

这是我当前的代码:

//HTTP Request

            let parameters = [

                "query":name![0] as? String,

                "lang":"en-US",

                "sessionID":"yaydevdiner"

            ];



            //create the url with URL

            let url = URL(string: "https://api.api.ai/v1/query")! //change the url



            //create the session object

            let session = URLSession.shared



            //now create the URLRequest object using the url object

            var request = URLRequest(url: url)

            request.httpMethod = "POST" //set http method as POST



            do {

                request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

            } catch let error {

                print(error.localizedDescription)

            }



            request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            request.addValue("Bearer f786fef55008491fb8422cea2be85eb1", forHTTPHeaderField: "Authorization")



            //create dataTask using the session object to send data to the server

            let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in



                guard error == nil else {

                    return

                }



                guard let data = data else {

                    return

                }



                do {

                    //create json object from data

                    if let json = try JSONSerialization.jsonObject (with: data, options: .mutableContainers) as? [String:Any] {

                        self.Response.setText(json["result"]["string"]);

                    }

                } catch let error {

                    print(error.localizedDescription)

                }

            })

            task.resume()

        }

Response是一个文本标签。

json["result"]这段代码给了我一个错误,说我应该在 and 之间加一个问号 ["speech"]。当我这样做时,它给了我另一个错误,说“Type Any 没有下标成员”。

标签: jsonswifthttpdialogflow-es

解决方案


好的,我想通了。

因为 XCode 会自动使用 watchOS 应用程序制作 iOS 应用程序,所以我决定尝试在 iOS 应用程序中进行调试,直到获得 HTTP 请求和 JSON 解析正确。

在 JSONSerialization if 语句中,我不得不添加另一个 if 语句:

if let result = responseJSON["result"] as? [String:Any]{
self.Response.setText(result!["speech"] as? String ?? "Network error Occurred")
}

感谢vadian的帮助!


推荐阅读