【发布时间】:2016-05-06 15:31:28
【问题描述】:
项目文件:
https://jumpshare.com/v/Otai3BBXYwfvyz8jb53k
(最好查看这些以了解项目结构)
问题:
好的,所以我正在关注tutorial,它创建了一个带有标题和单元格内容的 UITableView。
代码运行良好,现在我想扩展该教程并使用 alamofire 和 SwiftyJSON 动态加载该内容。
教程中使用的代码是这样的:
func getSectionsFromData() -> [Sections] {
var sectionsArray = [Sections]()
let animals = Sections(title: "Animals", objects: ["Cats", "Dogs", "Birds", "Lions"])
sectionsArray.append(animals)
return sectionsArray
}
我尝试做的是:
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 (year, content) in subJson {
let title = year
let objects = content
sectionsArray.append(Sections(title: title, objects: objects))
}
}
}
case .Failure(let error):
print(error)
}
}
如果我打印出它们在控制台中显示的结果 - 所以我知道 JSON 的获取和循环是有效的。然后我添加了
let title = year
let objects = content
sectionsArray.append(Sections(title: title, objects: objects))
但是在这一行:
sectionsArray.append(Sections(title: title, objects: objects))
我收到此错误:
无法将“JSON”类型的值转换为预期的参数类型“[String]”
这是我正在使用的 JSON:
{"posts": [
{
"Category1": [
"Post1cat1"
],
"Category2": [
"Post1cat2",
"Post2cat2"
]
}
]}
有人可以帮助我吗? 我可能走错了方向我想循环遍历 JSON 并将类别显示为标题,并将帖子显示在表格的单元格中。
编辑:2016 年 1 月 29 日
所以,我将循环更改为:
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!}))
}
}
}
仍然没有运气。当我添加一些打印(在: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"]
部分(标题:“Category1”,项目:[“Post1cat1”])
--
类别2
["Post1cat2", "Post2cat2"]
部分(标题:“Category2”,项目:[“Post1cat2”,“Post2cat2”])
这表明信息在那里,但是当我运行应用程序时,仍然没有结果来自他的 JSON,只是最初定义的部分和上面的单元格。
【问题讨论】:
标签: json swift uitableview alamofire swifty-json