我想做的是循环这些json结果;对于每个类别,在UITableView中创建一个标题,并为类别下的每个帖子创建一个tableview单元格
https://jumpshare.com/v/Otai3BBXYwfvyz8jb53k
出于某种原因,当我尝试追加到数组时,在for循环中形成它不会添加。
这是我的代码:
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!}))
我在控制台中得到了这个结果:
-
组别
[" Post1cat1"]
章节(标题:"类别1和#34;,项目:[" Post1cat1"])
-
类别2
[" Post1cat2"," Post2cat2"]
章节(标题:"类别2和#34;,项目:[" Post1cat2"," Post2cat2"])
然而,当我运行应用程序时 - 在tableview中显示的所有内容都是animals数组中的项目。
import Foundation
import Alamofire
import SwiftyJSON
class SectionsData {
let url = "https://api.myjson.com/bins/3nuvn";
var myArray: [String] = []
func getSectionsFromData() -> [Sections] {
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!}))
}
}
}
}
case .Failure(let error):
print(error)
}
}
sectionsArray.append(animals);
return sectionsArray
}
}
答案 0 :(得分:1)
带有完成块的代码应该是这样的:
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
})