Search code examples
jsonswiftuicollectionviewpushviewcontroller

How to push different view controller from collection view didSelectItemAt based on Json id in swift


My project contains collectionView.. but how to push different viewcontroller from didSelectItemAt based on json id.. and i have separate vewcontrollers for each id.. but i am unable to push different viewcontrolls with didSelectItemAt based on json id.

here is my Json for collectionView:

{
"financer": [
    {
        "id": "45",
        "icon": "https://hello.com//images/img1.png"
    }
    {
        "id": "40",
        "icon": "https://hello.com//images/img2.png"
     }
     .
     .
     .
   ]
 }

here is my home collectionview code:

import UIKit

struct JsonData {

var iconHome: String?
init(icon: String, tpe: String) {
    self.iconHome = icon
}
}

class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!

var itemsArray = [JsonData]()
var idArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()

    homeServiceCall()
    //Do any additional setup after loading the view.
    collectionView.delegate = self
    collectionView.dataSource = self
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return itemsArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell

    let aData = itemsArray[indexPath.row]
    cell.paymentLabel.text = aData.typeName

    if let url = NSURL(string: aData.iconHome ?? "") {
        if let data = NSData(contentsOf: url as URL) {
            cell.paymentImage.image = UIImage(data: data as Data)
        }
    }
    return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as! MakePaymentViewController
    self.navigationController?.pushViewController(nextViewController, animated: true)
    let indexPathHome = indexPath.row
    print("home collectionItem indexpath \(indexPathHome)")

}

//MARK:- Service-call

func homeServiceCall(){

    let urlStr = "https://dev.com/webservices/getfinancer"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

        guard let respData = data else {
            return
        }

        do{
            let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
            let financerArray = jsonObj["financer"] as! [[String: Any]]

            for financer in financerArray {

                let id = financer["id"] as! String
                let pic = financer["icon"] as? String
                print("home financer id \(id)")
                self.idArray.append(id)
                print("the home financer idsArray \(self.idArray.append(id))")
                self.itemsArray.append(JsonData(icon: pic ?? ""))
            }
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
        catch {
            print("catch error")
        }

    }).resume()
}
}

when I click on any item from collectionview i am able to push same view controller but i need to push different view controller based on json id. i dont know how to and where to use json id to push differnt viewcontroller using didselectItem atIndexPath. anyone please help me here.


Solution

  • Update your homeServiceCall function

    func homeServiceCall(){
    
        let urlStr = "https://dev.com/webservices/getfinancer"
        let url = URL(string: urlStr)
        URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
    
            guard let respData = data else {
                return
            }
    
            do{
                let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
                let financerArray = jsonObj["financer"] as! [[String: Any]]
    
                for financer in financerArray {
    
                    let id = financer["id"] as! String
                    let pic = financer["icon"] as? String
    
                    self.itemsArray.append(JsonData(icon: pic ?? ""))
                    self.idArray.append(id)
                }
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            }
            catch {
                print("catch error")
            }
    
        }).resume()
    }
    

    Create a string property called financerId in your MakePaymentViewController

    In your didSelect function

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
        if let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as? MakePaymentViewController {
            nextViewController.finacerId = idArray[indexPath.row]
          self.navigationController?.pushViewController(nextViewController, animated: true)
        }
    
    }
    

    Update

    for financer in financerArray {
          if let id = financer["id"] as? Int {
              self.idArray.append(id)
          }
    
          if let pic = financer["icon"] as? String {
              elf.itemsArray.append(JsonData(icon: pic))
          }
    }