Я пытаюсь получить значение ключа ["sub_department_name"] внутри ключа ["sub_depart"] из API, используя Alamofire и SwiftyJSON.
Это ответ API:
[
{
"main_department_id": "1",
"main_department_name": "mar",
"main_department_image": "8.jpg",
"sub_depart": [
{
"sub_department_id": "4",
"sub_department_name": "add\r\n",
"sub_department_image": "16.png"
},
{
"sub_department_id": "5",
"sub_department_name": "rol",
"sub_department_image": "10.jpg"
}
]
},
{
"main_department_id": "2",
"main_department_name": "fam ",
"main_department_image": "14.jpg",
"sub_depart": [
{
"sub_department_id": "6",
"sub_department_name": "fam wor",
"sub_department_image": "23.jpg"
}
]
},
{
"main_department_id": "3",
"main_department_name": "sau",
"main_department_image": "6.jpg",
"sub_depart": [
{
"sub_department_id": "7",
"sub_department_name": "sau",
"sub_department_image": "26.jpg"
},
{
"sub_department_id": "8",
"sub_department_name": "goo",
"sub_department_image": "31.jpg"
}
]
},
{
"main_department_id": "9",
"main_department_name": "try",
"main_department_image": "6.jpg",
"sub_depart": []
}
]
Вот модель, которую я использую:
class CategoriesDep: NSObject {
var depName: String
var depImage: String
var subName: String
init?(dict: [String: JSON]) {
guard let image = dict["main_department_image"]?.imagePath, !image.isEmpty else { return nil }
self.depImage = image
self.depName = (dict["main_department_name"]?.string)!
self.subName = (dict["sub_department_name"]?.string)!
}
И вот запрос get:
class func categoryDep (completion: @escaping(_ error: Error?, _ data: [CategoriesDep]?) -> Void) {
Alamofire.request(URLs.categoryDep).responseJSON { (response) in
switch response.result {
case.failure(let error):
completion(error,nil)
print(error)
case .success(let value):
let jsonData = JSON(value)
//print(jsonData)
guard let dataArray = jsonData.array else{
completion(nil , nil)
return
}
var main = [CategoriesDep]()
for data in dataArray {
if let data = data.dictionary , let result = CategoriesDep.init(dict: data) {
main.append(result)
print("good")
}
}
completion(nil, main)
}
}
}