我一直在View Controller中获取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的“绘图”值并使Firebase运行的能力
答案 0 :(得分:0)
在给定表示您的服务器响应的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
}
}
答案 1 :(得分:0)
您的问题是将结果从JSONSerialization
投射到AnyObject
。如果希望使用下标,则应将结果向下转换为字典类型,例如[String:Any]
if let myJson = try JSONSerialization.jsonObject(with: content, options: .mutableLeaves) as? [String:Any] {
// plot = myJson["Plot"] as? String ?? "Default value"
}
无论如何,宁愿学习有关Codable
的知识,并使用它代替JSONSerialization
。只需创建符合Decodable
协议的类/结构,然后使用JSONDecoder
解码Data
对象即可。