【问题标题】:Results won't append from JSON结果不会从 JSON 追加
【发布时间】:2016-04-21 16:07:27
【问题描述】:

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

我正在使用SwiftyJSON 进行解析。

变量杂务不会在方法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)
}

【问题讨论】:

    标签: ios arrays json swift swifty-json


    【解决方案1】:

    当你调用像NSURLSession.sharedSession().dataTaskWithURL 这样的异步方法时,它会在后台执行,所以无论你在这条指令实际执行后启动什么while 后台任务正在运行,因此当您查看数组时尚未填充您的数组。

    克服这个错误的一个简单方法是使用“回调”:一个闭包,一旦数据可用就会被执行。

    例如,我们添加一个回调

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

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 2016-01-29
      • 2012-03-23
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多