杰森和可变范围 [英] Json and variable scope

查看:179
本文介绍了杰森和可变范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的错误应该很明显,但是我找不到它;

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]()

我尝试使用该函数用一个遥远的json文件填充此数组

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

当我在viewDidLoad中调用我的函数然后打印我的全局数组时,它是空的(URL是正确的,json数据可以正确读取,当我在循环中读取附加在数组中的数据时,它将打印(因此)所需的值...)

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...)

预先感谢

推荐答案

下载需要时间.介绍另一种方法:

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

这篇关于杰森和可变范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆