Json and variable scope

不羁岁月 提交于 2020-01-07 03:17:06

问题


My error should be quite obvious but I can't find it;

I've a global variable initialized a the beginning of my class:

class InscriptionStageViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var lesSemaines = [String]()

I try to populate this array with a distant json file using that function

func getSemainesStages(){
        let url = URL(string: "http://www.boisdelacambre.be/ios/json/semaines.json")
        let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
            if let content = data {
                do {
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    let listeSemaines = myJson["semaine"] as! [[String:AnyObject]]
                    //print(listeSemaines)

                    for i in 0...listeSemaines.count-1 {
                        var tabSem = listeSemaines[i]
                        let intituleSemaine:String = tabSem["intitule"] as! String
                        //let dateSemaine:String = tabSem["date"] as! String

                        DispatchQueue.main.sync
                            {

                                self.lesSemaines.append(intituleSemaine)
                            }

                    }

                } catch
                {
                    print("erreur Json")
                }
            }

        }
        task.resume()
    }

When I call my function in the viewDidLoad and then I print my global array, it's empty (the URL is correct, the json data is read correctly and when I read the data appended in the array in the loop, it print the (so) needed value...)

Thanks in advance


回答1:


The download takes time. Introduce another methode:

func updateUi() {
    print(lesSemaines)
    //pickerView.reloadAllComponents()
}

And call it after the download finished:

func getSemainesStages(){
    // ... your code 
    let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
        // ... your code        
        for tabSem in listeSemaines{
             guard let intituleSemaine = tabSem["intitule"] as? String else {
                print("erreur Json")
                continue
            }
            self.lesSemaines.append(intituleSemaine)    
        }

        // update UI *after* for loop
        DispatchQueue.main.async {
            updateUi()   
        }
        // ... your code
    }
}



回答2:


I have updated your code to Swift 3. Please replace it with below code.

func getSemainesStages(){
    let url = URL(string: "http://www.boisdelacambre.be/ios/json/semaines.json")
    let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
        if let content = data {
            do {
                let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
                let listeSemaines = myJson["semaine"] as! [[String: Any]]

                for i in 0...listeSemaines.count-1 {
                    var tabSem = listeSemaines[i]
                    let intituleSemaine:String = tabSem["intitule"] as! String
                    self.lesSemaines.append(intituleSemaine)
                }
                print(self.lesSemaines)
            } catch {
                print("erreur Json")
            }
        }

    }
    task.resume()
}


来源:https://stackoverflow.com/questions/43184215/json-and-variable-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!