从函数外部的json获取数据

时间:2019-11-14 11:08:44

标签: json swift

我已经尝试了多个小时来获取数据,然后能够从获取功能之外访问数据而没有成功。随时询问我更多信息,但是以下是我的代码。

这是我的单例课程->

class QuestionClass{
    var q: Question?
    static let sharedInstance = QuestionClass()
    private init(){

    }

    func fetchUser(completion: @escaping ([Question]?) -> ()){
            let url = URL(string: "https://opentdb.com/api.php?amount=10.")!
            let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
                if let data = data {
                    do {
                        // parse json data and return it
                        let decoder = JSONDecoder()
                        let jsonDict = try decoder.decode(DATA.self, from: data)
                        completion(jsonDict.results)
                    } catch let parseErr {
                        completion(nil)
                        print("JSON Parsing Error", parseErr)
                    }
                }
            })
            task.resume()
    }
}

这是在viewController中完成的

       questionC.fetchUser {
            result in 
            if let temp = result{
                self.questionC.q = temp[0]
                var t = 0
                for (index, _) in temp[self.currentQuestion].incorrect_answers.enumerated(){
                    arrayNumbers.append(index)
                    t = index + 1
                }
                arrayNumbers.append(t)
                DispatchQueue.main.async {
                    for item in temp[self.currentQuestion].incorrect_answers{
                        let indexNumber = Int.random(in: 0 ... arrayNumbers.count-1)
                        self.view.addSubview(self.makeButtonWithText(text: item, x:locations[arrayNumbers[indexNumber]]._x, y:locations[arrayNumbers[indexNumber]]._y))
                            arrayNumbers.remove(at: indexNumber)
                    }
                }
                DispatchQueue.main.async {
                    self.questionField.text = temp[self.currentQuestion].question
                    self.view.addSubview(self.makeButtonWithText(text: temp[self.currentQuestion].correct_answer, x:locations[arrayNumbers[0]]._x, y:locations[arrayNumbers[0]]._y))
                }
            }
        }
        print(questionC.q)
        print(questionC.q?.correct_answer)

在最后几行中,我想从获取的数据中打印出值。但是他们是零,知道为什么吗?

2 个答案:

答案 0 :(得分:1)

将它们移动到result in if let temp = result{块内

questionC.fetchUser {
    result in if let temp = result{
        self.questionC.q = temp[0]
        var t = 0
        for (index, _) in temp[self.currentQuestion].incorrect_answers.enumerated(){
            arrayNumbers.append(index)
            t = index + 1
        }
        arrayNumbers.append(t)
        DispatchQueue.main.async {
            for item in temp[self.currentQuestion].incorrect_answers{
                let indexNumber = Int.random(in: 0 ... arrayNumbers.count-1)
                self.view.addSubview(self.makeButtonWithText(text: item, x:locations[arrayNumbers[indexNumber]]._x, y:locations[arrayNumbers[indexNumber]]._y))
                    arrayNumbers.remove(at: indexNumber)
            }
        }
        DispatchQueue.main.async {
            self.questionField.text = temp[self.currentQuestion].question
            self.view.addSubview(self.makeButtonWithText(text: temp[self.currentQuestion].correct_answer, x:locations[arrayNumbers[0]]._x, y:locations[arrayNumbers[0]]._y))
        }


        print(questionC.q)
        print(questionC.q?.correct_answer)

    }
}

答案 1 :(得分:0)

使用dispatchGroup可以达到目的(非常感谢MjZac向我指出了正确的方向)。问题似乎是我试图在fetchUser完成之前访问questionC.q。