Json 从内部循环快速追加到数组 需要
我想做的是循环这些json结果;对于每个类别,在UITableView中创建一个标题,对于类别下的每个帖子,创建一个tableview单元格 项目文件 问题 由于某种原因,当我尝试附加到数组时,For循环中的表单并没有添加 这是我的密码:Json 从内部循环快速追加到数组 需要,json,swift,uitableview,alamofire,swifty-json,Json,Swift,Uitableview,Alamofire,Swifty Json,我想做的是循环这些json结果;对于每个类别,在UITableView中创建一个标题,对于类别下的每个帖子,创建一个tableview单元格 项目文件 问题 由于某种原因,当我尝试附加到数组时,For循环中的表单并没有添加 这是我的密码: Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success:
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
for (_, subJson) in json {
for (index, data) in subJson {
for (title, objects) in data {
sectionsArray.append(Sections(title: title, objects: objects.self.arrayValue.map { $0.string!}))
}
}
}
}
case .Failure(let error):
print(error)
}
}
当我添加一些打印(在:sectionsArray.append下)以测试是否有数据时:
print("--")
print(title)
print(objects.self.arrayValue.map { $0.string!})
print(Sections(title: title, objects: objects.self.arrayValue.map { $0.string!}))
我在控制台中得到以下结果:
--
类别1
[“Post1cat1”]
章节(标题:“类别1”,项目:[“Post1cat1”])
--
类别2
[“Post1cat2”、“Post2cat2”]
章节(标题:“类别2”,项目:[“Post1cat2”、“Post2cat2”])
但是,当我运行应用程序时,在tableview中显示的只是动物数组中的项目
全视图控制器
带完成块的代码应如下所示:
func getSectionsFromData(completion: ([Sections]? -> Void)){
var sectionsArray = [Sections]()
let animals = Sections(title: "Animals", objects: ["Cats", "Dogs", "Birds", "Lions"])
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
for (_, subJson) in json {
for (_, data) in subJson {
for (title, objects) in data {
sectionsArray.append(Sections(title: title, objects: objects.self.arrayValue.map { $0.string!}))
}
}
}
}
sectionsArray.append(animals)
completion(sectionsArry)
case .Failure(let error):
print(error)
sectionsArray.append(animals)
completion(nil)
}
}
}
调用func时:
var sections: [Sections] = []
SectionsData().getSectionsFromData({ sectionsArray in
self.sections = sectionsArray
//reload your table with sectionsArray
})
您的
Alamofire
请求是异步执行的。可以,但这并不能回答问题。如何修复它?将数据添加到数组后,在表视图上调用reloadData()
。由于Alamofire
请求是异步的,因此应该在function@Breek-我不知道怎么做。现在,在这一行的SectionsTableViewController.Swift文件中:var sections:[sections]=SectionsData().getSectionsFromData()-我在callI中找不到参数#1的参数。很抱歉,我对编写swift非常陌生。我非常感谢您的帮助。您需要在某处声明您的部分
,然后调用SectionsData().getSectionsFromData({data in sections=data})
。这仍然是一个异步调用,因此您需要管理代码以采用该调用。节在section.swift文件的struct中定义。您认为您能够编辑该文件并可供下载吗?我对此感到非常困惑。
var sections: [Sections] = []
SectionsData().getSectionsFromData({ sectionsArray in
self.sections = sectionsArray
//reload your table with sectionsArray
})