Multiple views inside TableView Cell - ios

This is how my cell looks like
This is the structuring of my cell
I have a JSON format looks like this:
{
"status": true,
"session": true,
"make": "Ford",
"year": "2015",
"model": "EXPLORER",
"trim": "Base",
"engine": "3.5L V6 - Gas",
"make_id": "96",
"year_id": "100",
"model_id": "284",
"trim_id": "358",
"engine_id": "510",
"title": "Ford 2015 EXPLORER Base 3.5L V6 - Gas - Alternator",
"group_image": "http://www.orouad.com/test_aspns/image/catalog/Ford/67dc394bb5c7839fe09bcbae85210b90.svg",
"parts": [
{
"product_id": "7760",
"group_id": "317991",
"part_number": "DG1Z-10346-B",
"part_name": "Alternator",
"part_image": "http://www.orouad.com/test_aspns/image/cache/placeholder-130x130.png",
"description": "",
"part_index": "1",
"quantity": "0",
"price": "SAR 0.00",
"after_market": [],
"superseded": [
{
"part_id": "11695",
"part_no": "AA5Z*10346*B",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 0.00",
"quantity": "0"
},
{
"part_id": "12187",
"part_no": "GL*980*",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 0.00",
"quantity": "0"
}
]
},
{
"product_id": "7761",
"group_id": "318048",
"part_number": "DG1Z-10346-F",
"part_name": "Alternator",
"part_image": "http://www.orouad.com/test_aspns/image/cache/placeholder-130x130.png",
"description": "",
"part_index": "1",
"quantity": "0",
"price": "SAR 0.00",
"after_market": [],
"superseded": [
{
"part_id": "11581",
"part_no": "8A4Z*10346*A",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 0.00",
"quantity": "0"
},
{
"part_id": "12032",
"part_no": "DG1Z*10346*A",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 0.00",
"quantity": "0"
},
{
"part_id": "12186",
"part_no": "GL",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 7.00",
"quantity": "0"
}
]
},
{
"product_id": "7762",
"group_id": "318101",
"part_number": "GB5Z-10346-C",
"part_name": "Alternator",
"part_image": "http://www.orouad.com/test_aspns/image/cache/placeholder-130x130.png",
"description": "",
"part_index": "1",
"quantity": "0",
"price": "SAR 0.00",
"after_market": [],
"superseded": [
{
"part_id": "11848",
"part_no": "BL3Z-10346-A",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 0.00",
"quantity": "0"
},
{
"part_id": "12079",
"part_no": "DG1Z-10346-C",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 0.00",
"quantity": "0"
},
{
"part_id": "12186",
"part_no": "GL",
"manufacturer": null,
"description": "Alternator",
"price": "SAR 7.00",
"quantity": "0"
}
]
}
I want to show all "parts" as well as "aftermarket" and "superseded" parts if there is any value inside array "aftermarket" and "superseded" otherwise hide the aftermarket and superseded view and just show the parts view.
My problem is how do I show multiple views of aftermarket and superseded if there is multiple value inside these array.
This is the code to show if there is only one value in aftermarket or superseded
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return partsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "partsDetailCell") as! VehiclePartsDetailCell
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.borderWidth = 1
let partData = partsData[indexPath.row]
if (partData.afterMarket?.isEmpty)!{
cell.bottomView.isHidden = true
}else{
cell.bottomView.isHidden = false
cell.bottomPartLbl.text = partData.afterMarket![0].partNo
cell.bottomDesLbl.text = partData.afterMarket![0].description
cell.bottomPriceLbl.text = partData.afterMarket![0].price
}
cell.serialNoLbl.text = partData.partIndex
cell.partNoLbl.text = partData.partNumber
cell.descriptionLbl.text = partData.partName
cell.priceLbl.text = partData.price
cell.cartBtn.setImage(UIImage(named: "cart.png"), for: .normal)
return cell
}
I anyone provide any suggestion on how to populate data or to use multiple cells inside tableview.

This is pseudo code just for example, you have to modify it.
First you have to set cell size with this method
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return currentCellSize + partsData[indexPath.row].superseded.count * supersededSize + afmNormalHight * partsData[indexPath.row].afterMarket.count
}
After taht you need to change your cell creation to be like this
var currentCount = 0
for afterMarket in partData.afterMarke {
let afm = AfterMarketView()
afm.bottomPartLbl.text = partData.afterMarket![0].partNo
afm.bottomDesLbl.text = partData.afterMarket![0].description
afm.bottomPriceLbl.text = partData.afterMarket![0].price
afm.frmae = CGFrame(0, normalCellSize + afmNormalHight * currentCount, cell.frame.size.width, afmNormalHight)
currentCount++
cell.addSubview(afm)
}

Related

I am trying to create a heirarchy view. The view should expand and contract once clicked on each person

When clicked on each person , the subordinates list of that person should appear at the bottom. The whole list is dynamic .
{
"EmployeeId": "1",
"Name": "John",
"Position": "HR",
"Image": "",
"SubordinateCount": 6,
"Subordinates": [
{
"EmployeeId": "2",
"Name": "Sub john 1",
"Position": "Manager",
"Image": "",
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "3",
"Name": "Joseph",
"Position": "Admin",
"Image": "",
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "4",
"Name": "Raj",
"Position": "Software Developer",
"Image": "",
"SubordinateCount": 0,
"Subordinates": []
}
]
}
]
},
{
"EmployeeId": "5",
"Name": "Rahul",
"Position": "ERP Consultant",
"Image": "",
"SubordinateCount": 16,
"Subordinates": [
{
"EmployeeId": "6",
"Name": "Fam",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "7",
"Name": "Salman A Q",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "8",
"Name": "Mac",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "9",
"Name": "Mathew",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "10",
"Name": "Kim",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "11",
"Name": "Loren",
"Position": "Software Developer",
"Image": "",
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "12",
"Name": "Adam",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "13",
"Name": "Meera",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "14",
"Name": "MMM",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "15",
"Name": "Master",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "16",
"Name": "Michael",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "17",
"Name": "George",
"Position": "Consultant",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "18",
"Name": "Ahmedu A F",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "19",
"Name": "KKKK",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "20",
"Name": "xxx",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "21",
"Name": "DK",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
}
]
},
{
"EmployeeId": "22",
"Name": "HHHH",
"Position": "Engineer",
"Image": "",
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "23",
"Name": "Ar",
"Position": "Technical",
"Image": "",
"SubordinateCount": 0,
"Subordinates": []
}
]
},
{
"EmployeeId": "24",
"Name": "Sun",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "25",
"Name": "AAAA",
"Position": null,
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
}
]
},
{
"EmployeeId": "26",
"Name": "CCCC",
"Position": "Consultant",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "27",
"Name": "Jaaaa",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 2,
"Subordinates": [
{
"EmployeeId": "28",
"Name": "Jay",
"Position": "Ssssss",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "29",
"Name": "NNNN",
"Position": "Sssss",
"Image": null,
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "30",
"Name": "Jo",
"Position": "Engineer",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
}
]
}
]
}
]
}
This is the json to be used .I have tried with collection view inside table view.But failed when i try to delete a row when user moves to the top and clicks on a new person . I have seen many libraries showing tree structure for table view . But i think that cannot be used here .
This is what i have tried so far.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return selectedIndexes.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var bottomCell : SubordinatesTableViewCell! = self.Extableview.dequeueReusableCell(withIdentifier: "SubordinatesTableViewCell") as? SubordinatesTableViewCell
if bottomCell == nil {
let nib:Array = Bundle.main.loadNibNamed("SubordinatesTableViewCell", owner: self, options: nil)!
bottomCell = nib[0] as? SubordinatesTableViewCell
}
bottomCell.empLevel = indexPath.row
bottomCell.delegate = self
bottomCell.subordinateDetails = self.subordinatesList
return bottomCell
}
extension CurrentVC : SubordinateCellDelegate {
func employeeClicked(row: Int?, index: Int?) {
self.subordinatesList = self.heirarchy?.subordinates
self.currentHeirarchyLevel = row! + 1
if self.Extableview.numberOfRows(inSection: 0) > row! + 1 {
var newIndexes = [Int]()
if row! == 0 {
self.selectedIndexes.removeAll()
self.selectedIndexes.append(index!)
}else {
for i in 0..<(row! + 1) {
newIndexes.append(selectedIndexes[i])
}
self.selectedIndexes = newIndexes
self.selectedIndexes.append(index!)
}
for i in 0..<row! + 1 {
self.subordinatesList = self.subordinatesList?[self.selectedIndexes[i]].subordinates
print(subordinatesList)
}
if subordinatesList?.count ?? 0 > 0 {
self.Extableview.reloadRows(at: [IndexPath(row: self.currentHeirarchyLevel, section: 0)], with: .fade)
}else {
for i in 0..<self.Extableview.numberOfRows(inSection: 0) {
if i > row! {
self.Extableview.beginUpdates()
self.Extableview.deleteRows(at: [IndexPath(row: 1, section: 0)], with: .fade)
}
}
self.numOfsections = row! + 1
self.Extableview.endUpdates()
}
}else {
self.selectedIndexes.append(index!)
for i in 0..<row! + 1 {
self.subordinatesList = self.subordinatesList?[self.selectedIndexes[i]].subordinates
}
if self.subordinatesList?.count ?? 0 > 0 {
self.Extableview.beginUpdates()
self.numOfsections = row! + 2
self.Extableview.insertRows(at: [IndexPath(row: row! + 1, section: 0)], with: .none)
self.Extableview.endUpdates()
}else {
for i in 0..<self.Extableview.numberOfRows(inSection: 0) {
if i > row! {
self.Extableview.beginUpdates()
self.numOfsections = row! + 1
self.Extableview.deleteRows(at: [IndexPath(row: 1, section: 0)], with: .fade)
}
}
self.Extableview.endUpdates()
}
}
}
}
Declare 4 variables ,
var heirarchy : Subordinates?
var numOfRows = 0
var subordinatesList : [Subordinates]?
var subList = [[Subordinates]?]()
Once you get the json response ,
self.numOfRows += 1
self.subordinatesList?.append(self.heirarchy!)
self.subList.append([self.heirarchy!])
Create a delegate function for collection view item click as below .
func employeeClicked(row: Int?, index: Int?, subordinates: [Subordinates]?) {
if (subordinates?.count ?? 0) > 0 {
self.subordinatesList = subordinates
if numOfRows > row! + 2 {
self.tableView.beginUpdates()
for i in (row! + 1)..<tableView.numberOfRows(inSection: 0) {
self.tableView.deleteRows(at: [IndexPath(row: i, section: 0)], with: .fade)
self.numOfRows = numOfRows - 1
self.subList.removeLast()
}
self.subList.append(self.subordinatesList)
self.numOfRows = row! + 2
self.tableView.insertRows(at: [IndexPath(row: row! + 1, section: 0)], with: .fade)
self.tableView.endUpdates()
}
else if numOfRows == row! + 2 {
self.subList[row! + 1] = self.subordinatesList
self.tableView.reloadRows(at: [IndexPath(row: row! + 1, section: 0)], with: .fade)
}else {
self.subList.append(self.subordinatesList)
self.numOfRows = row! + 2
self.tableView.insertRows(at: [IndexPath(row: row! + 1, section: 0)], with: .fade)
}
}else {
if numOfRows > row! + 1 {
self.tableView.beginUpdates()
for i in (row! + 1)..<tableView.numberOfRows(inSection: 0) {
self.tableView.deleteRows(at: [IndexPath(row: i, section: 0)], with: .fade)
self.numOfRows = numOfRows - 1
self.subList.removeLast()
}
self.tableView.endUpdates()
}
}
self.tableView.scrollToBottom()
}
}
In tableview cellfor row delegate use the value of sublist array.
Hope this helps you . I checked the code and it is working fine for me.

Binding JSON data to TableView and CollectionView

I am trying to create a table view with a collection view in each cell. My JSON structure is like Main Menu title for the tv cell and in each main object, I receive a submenu, whose data I want to use in the collection view.
The issue I am facing is in using indexes of table cell and collection cell to get the nested data. Here is my JSON
"MainMenu": [
{
"ID": 8,
"MasterID": 12,
"Title": "Payment",
"Image": "image.png",
"SubMenu": [
{
"ID": 9,
"Title": "My Bill",
"Image": "image.png"
},
{
"ID": 10,
"Title": "Electricity ",
"Image": "image.png"
},
{
"ID": 11,
"Title": "Gas",
"Image": "image.png"
},
{
"ID": 12,
"Title": "Telephone",
"Image": "image.png"
},
{
"ID": 13,
"Title": "Water",
"Image": "image.png"
}
]
},
{
"ID": 40,
"MasterID": 14,
"Title": "Services",
"Image": "image.png",
"SubMenu": [
{
"ID": 32,
"Title": "Upload Slip",
"Image": "image.png"
},
{
"ID": 41,
"Title": "SRY (Self Reliant Youth)",
"Image": "image.png"
},
{
"ID": 42,
"Title": "Dollor Product Purchase ",
"Image": "image.png"
},
{
"ID": 43,
"Title": "ARY Coin Redemption",
"Image": "image.png"
},
{
"ID": 44,
"Title": "Pay Via QR",
"Image": "image.png"
},
{
"ID": 45,
"Title": "Card Request",
"Image": "image.png"
}
]
},
{
"ID": 14,
"MasterID": 8,
"Title": "Mobile Balance",
"Image": "image.png",
"SubMenu": [
{
"ID": 15,
"Title": "My Mobile",
"Image": "image.png"
},
{
"ID": 16,
"Title": "Mobilink",
"Image": "image.png"
},
{
"ID": 17,
"Title": "Telenor",
"Image": "image.png"
},
{
"ID": 18,
"Title": "Ufone",
"Image": "image.png"
},
{
"ID": 19,
"Title": "Warid",
"Image": "image.png"
},
{
"ID": 20,
"Title": "Zong",
"Image": "image.png"
}
]
},
{
"ID": 46,
"MasterID": 6,
"Title": "Help",
"Image": "image.png",
"SubMenu": [
{
"ID": 47,
"Title": "Call",
"Image": "image.png"
},
{
"ID": 48,
"Title": "Chat",
"Image": "image.png"
},
{
"ID": 49,
"Title": "Email",
"Image": "image.png"
},
{
"ID": 50,
"Title": "Others",
"Image": "image.png"
},
{
"ID": 51,
"Title": "VAS / SMS",
"Image": "image.png"
}
]
},
{
"ID": 21,
"MasterID": 5,
"Title": "Fund Transfer",
"Image": "image.png",
"SubMenu": [
{
"ID": 22,
"Title": "To Other ARY Wallet",
"Image": "image.png"
},
{
"ID": 23,
"Title": "To Bank Account",
"Image": "image.png"
}
]
},
{
"ID": 34,
"MasterID": 1,
"Title": "$ & MilliGold Deal",
"Image": "image.png",
"SubMenu": [
{
"ID": 35,
"Title": "$ Deposit",
"Image": "image.png"
},
{
"ID": 36,
"Title": "$ Purchase",
"Image": "image.png"
},
{
"ID": 37,
"Title": "$ Time Games",
"Image": "image.png"
},
{
"ID": 38,
"Title": "Scan for Bid",
"Image": "image.png"
}
]
}
],
"CustomerAccountInformation": []
}
Please guide me how can I use my JSON objects each in different tablecell.
Here is what I have tried:
TVCell
cell.titleLabel.text = menu?.mainMenu?[indexPath.row].title ?? "Our services"
CollectionCell
cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[indexPath.row].subMenu?[indexPath.row].image)!)!)
First, in your tableview cell, set the tag of the collectionview to indexPath.row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : TVCell = tableview.dequeueReusableCell(withIdentifier: "TVCell", for: indexPath) as! TVCell
cell.myCollectionView.tag = indexPath.row
return cell
}
Now in your collectionview cell you can parse the data like following
let index = cell.tag
cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[index].subMenu?[indexPath.row].image)!)!)

How to load that JSON on tableview?

I have problem with parse json to collectionview
That is my JSON:
{
"statusCode": 200,
"message": "Список курсов",
"content": [
{
"id": 1,
"slug": "kurs-a1",
"title": "Курс А1",
"can_access": 1,
"passed": 1,
"sections": [
{
"id": 1,
"slug": "razdel-1",
"title": "Раздел 1",
"can_access": 1,
"passed": 1,
"lessons": [
{
"id": 1,
"position": 1,
"title": "Сәлемдесу",
"slug": "salemdesu",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 1
},
{
"id": 3,
"position": 2,
"title": "Танысу",
"slug": "tanysu",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 1
}
]
},
{
"id": 2,
"slug": "razdel-2",
"title": "Раздел 2",
"can_access": 1,
"passed": 0,
"lessons": [
{
"id": 4,
"position": 3,
"title": "Бұл – менің отбасым",
"slug": "bul-menin-otbasym",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 0
},
{
"id": 5,
"position": 4,
"title": "Жасы нешеде?",
"slug": "zhasy-neshede",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 0
}
]
},
{
"id": 3,
"slug": "razdel-3",
"title": "Раздел 3",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 7,
"position": 5,
"title": "Туған күн",
"slug": "tugan-kun",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 9,
"position": 6,
"title": "Құттықтау",
"slug": "kuttyktau",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 4,
"slug": "razdel-4",
"title": "Раздел 4",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 10,
"position": 7,
"title": "Адам келбеті",
"slug": "adam-kelbeti",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 12,
"position": 8,
"title": "Адамның мінез-құлқы",
"slug": "adamnyn-minez-kulky",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 5,
"slug": "razdel-5",
"title": "Раздел 5",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 13,
"position": 9,
"title": "Менің мамандығым",
"slug": "menin-mamandygym",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 15,
"position": 10,
"title": "Кім болып жұмыс істейді?",
"slug": "kim-bolyp-zhumys-istejdi",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 6,
"slug": "razdel-6",
"title": "Раздел 6",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 16,
"position": 11,
"title": "Жұмыс орны",
"slug": "zhumys-orny",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 17,
"position": 12,
"title": "Жұмыс күні",
"slug": "zhumys-kuni",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 7,
"slug": "razdel-7",
"title": "Раздел 7",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 19,
"position": 13,
"title": "Тесты ЦОР-а",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 20,
"position": 14,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 8,
"slug": "razdel-8",
"title": "Раздел 8",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 22,
"position": 15,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 23,
"position": 16,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 9,
"slug": "razdel-9",
"title": "Раздел 9",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 25,
"position": 17,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 27,
"position": 18,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 10,
"slug": "razdel-10",
"title": "Раздел 10",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 28,
"position": 19,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 29,
"position": 20,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 11,
"slug": "razdel-11",
"title": "Раздел 11",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 32,
"position": 21,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 33,
"position": 22,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 12,
"slug": "razdel-12",
"title": "Раздел 12",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 34,
"position": 23,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 35,
"position": 24,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
}
]
}
]
}
I decode it and i want parse it to collectionview.
How can i get content [{sections[{lessons[{title}]}]}]?
I made a request
func numberOfSections(in collectionView: UICollectionView) -> Int {
return arrData1.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let dn = arrData1[section]
let st = dn.sections?[section]
return (st?.lessons?.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "main_cell", for: indexPath) as! MainCollectionViewCell
cell.lesson_text_1.text = arrData1.first?.sections?[indexPath.item].title
// cell.lesson_img_1.image = UIImage(named: lesson_image_1[indexPath.row])
// cell.lesson_text_1.text = lesson_text_1[indexPath.row]
return cell
}
but it return 2 cell to me
But i need 24 lessons!
Thank you
Decoding
struct Welcome: Codable {
let statusCode: Int
let message: String
let content: [Content]
}
struct Content: Codable {
let id: Int
let slug, title: String
let canAccess: Int?
let passed: Int
let sections: [Content]?
let lessons: [Lesson]?
enum CodingKeys: String, CodingKey {
case id, slug, title
case canAccess = "can_access"
case passed, sections
case lessons = "lessons"
}
}
struct Lesson: Codable {
let id, position: Int
let title, slug: String
let image: String
let canAccess: Int?
let passed: Int
enum CodingKeys: String, CodingKey {
case id, position, title, slug, image
case canAccess = "can_access"
case passed
}
}
api call function
let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let data_new = try decoder.decode(Welcome.self, from: data)
DispatchQueue.main.async {
self.tableview.reloadData()
self.arrData1 = data_new.content
print(data_new)
}
} catch {
print("Error in CheckNew is : \n\(error)")
}
}
mData.resume()
enter image description here
Although the JSON structure is quite similar I recommend to use separate structs for Section and Lesson.
Another benefit is you get rid of all optionals
struct Welcome: Codable {
let statusCode: Int
let message: String
let content: [Content]
}
struct Content: Codable {
let id: Int
let slug, title: String
let canAccess: Int
let passed: Int
let sections: [Section]
}
struct Section: Codable {
let id: Int
let title, slug: String
let canAccess: Int
let passed: Int
let lessons: [Lesson]
}
struct Lesson: Codable {
let id, position: Int
let title, slug: String
let image: URL
let canAccess: Int
let passed: Int
}
As you are using the .convertFromSnakeCase strategy all coding keys are redundant.

SwiftyJSON Item At Index Not Working

I have the following dummy JSON data:
{
"folder": {
"id": 1,
"name": "Home",
"parent_folder_id": null,
"num_of_items": 10,
"num_of_items_complete": 10,
"children": {
"folders": [
{
"id": 2,
"name": "Identification",
"num_of_items": 4,
"num_complete": 4
},
{
"id": 3,
"name": "House and Household Equipment",
"num_of_items": 6,
"num_complete": 2
},
{
"id": 4,
"name": "Insurance",
"num_of_items": 4,
"num_complete": 3
},
{
"id": 5,
"name": "Owned Items",
"num_of_items": 6,
"num_complete": 5
}
],
"input_fields": [
{
"id": 1,
"key": "Something",
"value": "Dark Side",
"type": "text"
}
],
"shortcuts": [
]
}
}
}
And I need to access each child in "children" with an INDEX rather than by it's NAME for a collectionView:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.data["folder"]["children"][section].count
}
But it always returns 0 for the count. Is there anyway I can do this?
Try with this:
return self.data["folder"]["children"]["folders"].count
I think is the only way you can do it.

way to get value for address in this case? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
{
"status": "true",
"message": "11 records found",
"response": [
{
"name": "1",
"address": "565400-",
"phone": "",
"gym_email": "",
"images": ""
},
{
"name": "123",
"address": "102-",
"phone": "",
"gym_email": "1#2.com",
"images": ""
},
{
"name": "Burn Gym & Spa",
"address": "Sector 11,HaryanaPanchkula-134101",
"phone": "",
"gym_email": "1#2.com",
"images": "a:1:{i:0;s:18:\"1478177269200.jpeg\";}"
},
{
"name": "Burn Gym",
"address": "NAC,ManimajraChandigarhPanchkula-134112",
"phone": "",
"gym_email": null,
"images": ""
},
{
"name": "Burn Gym & Spa",
"address": "Sector 11,ChandigarhAmbala-160101",
"phone": "585888",
"gym_email": "1#2.com",
"images": ""
},
{
"name": "test gym",
"address": "Sector 11,HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "1#2.com",
"images": "a:1:{i:1;s:17:\"1478579644341.png\";}"
},
{
"name": "test gym",
"address": "Sector 12HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "",
"images": ""
},
{
"name": "new gym",
"address": "sector 11HaryanaPanchkula-134112",
"phone": "789654123",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 11HaryanaPanchkula-134101",
"phone": "8054233444",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 4HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 11HaryanaPanchkula-134101",
"phone": "8054233444",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
}
]
}
You can get the value of address as:
guard let response = json["response"] as? [[String:AnyObject]] else {
print("Nothing here")
return
}
then you can get address from the response array by looping,
for data in response {
print(data["address"] as? String)
}
if((jsonResult) != nil) {
let swiftyJsonVar = jsonResult!
do {
if let dicObj = swiftyJsonVar as? NSDictionary {
print("Response is dictionary")
print(dicObj)
let arrObj = dicObj["response"] as NSArray
// Then iterate your arrObj and do as per your need.
//for eg.
arrObj[0]["address"]
}
}
}
addressLabel.text=[[[mdict objectForKey:#"response"]objectAtIndex:indexPath.row]valueForKey:#"address"];

Resources