我想为我的 REST API 使用 Alamofire 和 SwiftyJSON。我已经访问了根 JSON,但我无法访问 JSON 的对象。
这是我的 json 结果:
[
{
"ID": 1,
"name": "JABODETABEK",
"cabang": [
{
"ID": 1,
"wilayah_id": 1,
"name": "Jembatan Lima"
},
{
"ID": 2,
"wilayah_id": 1,
"name": "Kebon Jeruk"
}
]
},
{
"ID": 2,
"name": "Sumatra Selatan dan Bangka Belitung",
"cabang": [
{
"ID": 6,
"wilayah_id": 2,
"name": "A. Yani - Palembang"
},
{
"ID": 7,
"wilayah_id": 2,
"name": "Veteran - Palembang"
}
]
}
}
使用这段代码:
Alamofire.request(url).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar.arrayObject {
self.productArray = resData as! [[String:AnyObject]]
print("MyArray: \(self.productArray)")
}
}
}
我的表格 View :
func numberOfSections(in tableView: UITableView) -> Int {
return self.productArray.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dic = productArray[section]
return dic["name"] as? String
}
func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
return (((?)))
}
请帮助我使用 Alamofire 和 SwiftyJSON 查看我的 tableView 单元格中的数据。我怎样才能访问这些数据?我的意思是如何获得 numberOfRowsInSection
?
最佳答案
试试这个:
Alamofire.request("url").responseJSON { (responseData) -> Void in
if let data = response.data {
guard let json = try? JSON(data: data) else { return }
self.productArray = json.arrayValue //productArray type must be [[String:AnyObject]]
}
更新 tableView 委托(delegate)函数之后:
func numberOfSections(in tableView: UITableView) -> Int {
return self.productArray.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dic = productArray[section]
return dic["name"].string
}
func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
return productArray[sectionInd]["cabang"].arrayValue.count
}
关于ios - 使用 Alamofire 和 SwiftyJSON 处理 JSON 并在 Swift 中添加到 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53256086/