首页 > 解决方案 > 导入 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 运行的能力

标签: jsonswiftfirebasegoogle-cloud-firestore

解决方案


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
    }
}

推荐阅读