json - 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 没有下标成员”。
解决方案
好的,我想通了。
因为 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的帮助!
推荐阅读
- javascript - 如何根据javascript中的另一个数组对数组进行排序?
- javascript - 将对象值与同一数组中的其他对象值进行比较
- spring - 无法在项目上执行目标 org.sonarsource.scanner.maven:sonar-maven-plugin:3.7.0.1746:sonar (default-cli)
- html - 如果原始图像不可见或出现错误,如何在 Html 中设置默认图像
- java - 如何将 Scala List[String] 转换为旧版 Java List
- python - 附加到关系
- python - 如何在python中重新缩放箱线图的y轴
- python - 缺少 1 个必需的位置参数:“密钥”加密
- javascript - 未捕获(承诺中)类型错误:无法读取 null 的属性“0”。如果超过 4 个标记,谷歌地图地理编码器
- javascript - 简单的香草 JavaScript 事件侦听器不起作用