结果不会附加JSON

我正在使用的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) } 

当您调用NSURLSession.sharedSession().dataTaskWithURL异步方法时NSURLSession.sharedSession().dataTaskWithURL在后台执行,因此在后台任务运行时实际执行该指令之后启动的任何内容,因此当您查看时,您的arrays尚未填充它。

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

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

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