结果不会从 JSON 追加

Results won't append from JSON

我正在使用的JSON文件:https://api.myjson.com/bins/49jw2

我正在使用 SwiftyJSON 进行解析。

不会在方法外填充变量 choress parseJson

var chores: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    tfWhat.delegate = self
    tfHowMuch.delegate = self

    loadJson()

    // wont even print
    for chore in self.chores {
        print("beschrijving: " + chore)
    }

    // prints 0
    print(chores.count)
}

func loadJson() -> Void {
    let url = NSURL(string: "https://api.myjson.com/bins/49jw2")

    NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
        } else {
            if let data = data {
                let json = JSON(data: data)

                self.parseJson(json["appdata"]["klusjes"][])
            } else {
                print("no data")
            }
        }
    }).resume()
}

func parseJson(jsonObject : JSON) -> Void {
    for (_, value) in jsonObject {
        self.chores.append(value["beschrijving"].stringValue)
    }

    // prints:
    // beschrijving: Heg knippen bij de overburen
    // beschrijving: Auto van papa wassen
    for chore in self.chores {
        print("beschrijving: " + chore)
    }

    // prints:
    // 2
    print(chores.count)
}

当你调用 异步方法 时,比如 NSURLSession.sharedSession().dataTaskWithURL 它会在后台 执行 ,所以无论你在之后启动什么该指令实际上执行 后台任务是 运行,因此当您查看它时,您的数组尚未填充

克服这个错误的一个简单方法是使用 "callback":闭包 一旦数据可用

例如,让我们添加一个回调

(json: JSON)->()

loadJson方法:

func loadJson(completion: (json: JSON)->())

并在数据可用的地方拨打电话:

func loadJson(completion: (json: JSON)->()) {
    let url = NSURL(string: "https://api.myjson.com/bins/49jw2")
    NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
        } else {
            if let data = data {
                // the callback executes *when the data is ready*
                completion(json: JSON(data: data))
            } else {
                print("no data")
            }
        }
    }).resume()
}

并将它与这样的尾随闭包一起使用:

loadJson { (json) in
    // populate your array, do stuff with "json" here, this is the result of the callback
}