结果不会从JSON追加 [英] Results won't append from JSON
问题描述
我正在使用的JSON文件: https://api.myjson.com/bins/49jw2
The JSON file I am using: 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
它会在后台执行 ,因此无论您在 后台任务运行时实际执行了该指令之后启动什么,因此您的数组在还时不会被填充。
When you call an asynchronous method like NSURLSession.sharedSession().dataTaskWithURL
it gets executed in the background, so whatever you launch just after this instruction is actually executed while the background task is running, so your array is not populated yet when you look at it.
一种解决此错误的简单方法是使用回调 :一个在数据可用后将执行的闭包。
A simple way to overcome this mistake is to use a "callback": a closure that will be executed once the data is available.
例如,l等添加回调
(json: JSON)->()
到 loadJson
方法:
func loadJson(completion: (json: JSON)->())
并将调用放置在数据可用的地方:
and place the call where the data will be available:
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()
}
并使用像这样的结尾闭包:
and use it with a trailing closure like this:
loadJson { (json) in
// populate your array, do stuff with "json" here, this is the result of the callback
}
这篇关于结果不会从JSON追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!