json - 导入 Firebase 导致 JSON 获取不明确
问题描述
我一直在我的视图控制器中获取 JSON,我需要一个函数来将同一个 VC 中的数据添加到 firebase,因此导入了 Firebase(Pods firebase core、auth 和 firestore),现在它给我一个错误的 JSON 获取它是不明确的使用“下标”
func getDetails(link: URL!) {
var plot : String = " "
let task = URLSession.shared.dataTask(with: link!) { (data, response, error) in
if error != nil
{
print("error")
}
else
{
if let content = data
{
do
{
//JSON results
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableLeaves) as AnyObject
//myJson ~~~ ["Plot"] Ambiguous use of 'subscript'
plot = myJson["Plot"] as! String
}
catch
{
print("error in JSONSerialization")
}
}
}
}
task.resume()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
self.plot.text = plot
})
}
我很想保持选择 JSON 的“Plot”值并让 firebase 运行的能力
解决方案
ModelObject
给定一个代表服务器响应的结构或类,这是我将如何重写此方法的方法。
func getDetails(link: URL!) {
var plot = " "
let group = DispatchGroup()
group.enter()
let task = URLSession.shared.dataTask(with: link!) { (data, response, error) in
defer { group.leave() }
guard error == nil else {
print(error)
return
}
if let content = data {
do {
let modelObject = try JSONDecoder().decode(ModelObject.self, from: data)
plot = modelObject.plotString
}
catch {
print(error)
}
}
}
task.resume()
group.notify(queue: DispatchQueue.main) {
self.plot.text = plot
}
}
推荐阅读
- java - 访问 getter 是私有的类的字段
- c++ - 打印所有 A 链表的元素 (C++)
- android - Proguard 功能和配置
- python - 使用数据类和字典来解决“盒子问题”
- android - 红米 Note 4 中的 ARCORE
- node.js - 如何使用 Chartjs + Nodejs + Express + Api 消耗在服务器端实时生成图表?
- c - char输入而不是int时的C无限循环
- python - IndexError: list out of range for [0] 尝试在 python 中抓取表
- c - Valgrind 和分配/释放内存的简单问题
- reactjs - 如何在 React Native 中的其他对象数组内的对象数组中添加值?