我在执行Alamofire调用并将JSON数据附加到全局数组时遇到了一些麻烦,我真的开始强调。
据我所知,在进行API调用时,它是在异步线程中完成的。然而,在研究了这个问题后,我已经按照建议进行了操作,但是我迷路了,因为在每个人的例子中他们只打印数据,这是有效的,但当我尝试将数据附加到数组时我仍然得数为0。
class SomeClass: UIViewController {
var categories = [Int]()
@IBOutlet var labels: [UILabel]!
override func viewDidLoad() {
super.viewDidLoad()
self.getJSON() { response in
self.populateArray(json: response)
}
//This prints 0 :(
print("Size: \(categories.count)")
var count = 1
for lbl in labels {
for var i in 0..<categories.count {
//Obviously this never computes so they all are black instead of some being red
lbl.tintColor = count == categories[i] ? UIColor.Red : UIColor.Black
}
}
public func getJSON(completionhandler: @escaping (JSON) -> ()) () {
Alamofire.request("some url").responseJSON { response in
switch response.result {
case .success:
let jsonData = JSON(data: response.data!)
completionHandler(jsonData)
case .failure(let error):
print(error)
}
}
}
public func populateArray(json: JSON) -> () {
//JSON still prints fine
print(json)
for (index, subJson):(String, JSON) in json {
//Again, prints fine
print(subJson["catID"].int!)
self.categories.append(subJson["catID"].ind!)
}
}
}
有谁知道我做错了什么?或者如果它首先是可以实现的,如果没有,是否有替代方案可以实现我的目标?
非常感谢。
答案 0 :(得分:1)
如果您希望代码在getJson
之后直接执行,那么您需要将该代码放在闭包中。
self.getJSON() { response in
self.populateArray(json: response)
print("Size: \(categories.count)")
var count = 1
for lbl in labels {
for var i in 0..<categories.count {
lbl.tintColor = (count == categories[i] ? UIColor.Red : UIColor.Black)
}
}
}