简体   繁体   中英

How to pushViewController from collectionView didSelectItemAt indexPath according to json id(means indexPath should match with json id) in Swift

My home Viewcontroller contains collectionView with items. generally when we click on any of item in collection view then we can push to other viewController by using didSelectItemAt indexPath. but here i am getting the each item image url along with its id from Json and in other viewController for each home id i am getting seperate url with oter fields form Json. when home id and other viewcontroller id matches then i need to push to that viewContoller using didSelectItemAt indexPath in home Viewcontroller.

Here is my code:

Home json:

"financer": [
            {
                "id": "45",
                "icon": "https://emi.com/Star/images/LSPUBLICSCHOOL_icon.png",
                "tpe": "L S PUBLIC SCHOOL",

            }
            {
               "id": "2",
               "icon": "https://emi.com/Star/images/MC_icon.png",
               "tpe": "MC",

            }
                 .
                 . 

HomeVC code:

import UIKit

struct JsonData {

var iconHome: String?
var typeName: String?
init(icon: String, tpe: String) {

    self.iconHome = icon
    self.typeName = tpe
}
}

class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!

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

    homeServiceCall()
    collectionView.delegate = self
    collectionView.dataSource = self
    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0)
    layout.itemSize = CGSize(width: 95, height: 95)
    collectionView?.collectionViewLayout  = layout
}
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 storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    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.emi.com/webservice/emi/getfinancer"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

        guard let respData = data else {
            return
        }
        guard error == nil else {
            print("error")
            return
        }
        do{
            DispatchQueue.main.async {
                self.activityIndicator.startAnimating()
            }
            let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
            print("the home json is \(jsonObj)")
            let financerArray = jsonObj["financer"] as! [[String: Any]]

            for financer in financerArray {

                let id = financer["id"] as! String
                let pic = financer["icon"] as? String
                let type = financer["tpe"] as! String
                self.itemsArray.append(JsonData(icon: pic ?? "", tpe: type))

            }

            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
        catch {
            print("catch error")
        }
        DispatchQueue.main.async {
            self.activityIndicator.stopAnimating()
        }
    }).resume()
}

}

otherVC Json:

for id 2 from home getting below json. for id 45 i am getting another json. if if home id 2 and other vcs id 2 matches then this fields need to display if id 45 matches then need to say will update soon message to display.

    {
    "loan_details": {
                      "id": "2",
                      "emi_amount": "1915",
                      "financer": "4",
                    }

Code;

import UIKit

class MakePaymentViewController: UIViewController {

@IBOutlet weak var serviceNumTextField: UITextField!
@IBOutlet weak var serviceNumLabel: UILabel!
@IBOutlet weak var dueamountLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func makePaymentButton(_ sender: Any) {

}
func makePaymentService(){

    let parameters = ["assessmentNo":  Int(serviceNumTextField.text ?? ""),
                      "id":"2",
                      ] as? [String : Any]

    let url = URL(string: "https://dev.emi.com/webservice/emi/getassment_details")
    var req =  URLRequest(url: url!)
    req.httpMethod = "POST"
    req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
    req.addValue("application/json", forHTTPHeaderField: "Accept")

    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
    req.httpBody = httpBody

    let session = URLSession.shared

    session.dataTask(with: req, completionHandler: {(data, response, error) in
        if let response = response {
            // print(response)
        }
        if let data = data {

            do{
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                print("the json for make payment \(json)")

                let loanDetails = json["loan_details"] as! [String : Any]
                let dueAmount = loanDetails["emi_amount"] as? String

                    DispatchQueue.main.async {

                        self.dueamountLabel.text = dueAmount

                    }

            }catch{
                print("error")
            }
        }
    }).resume()

}

@IBAction func searchBtnTapped(_ sender: Any) {
    makePaymentService()
}

}

for each home id i am getting separate json for MakePaymentViewController. if we select on 2nd id image from home then need to display those details in MakePaymentViewController. if we select 45 then those details.

here if i select any home item i am going to MakePaymentViewController and displaying id 2 details only. but i want individual details according to ids.

Please help me in code.

create variable on your second controller

class MakePaymentViewController: UIViewController {
    var id = ""
}

while pushing second Controller set the value of id based on selected Cell.

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        //let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as! MakePaymentViewController

        let selectedJson =  financerArray[indexpath.row]

        let indexPathHome = indexPath.row
        print("home collectionItem indexpath \(indexPathHome)")
nextViewController.id =  selectedJson["id"]

self.navigationController?.pushViewController(nextViewController, animated: true)

    }

pass value of Id to api.

func makePaymentService(){

    let parameters = ["assessmentNo":  Int(serviceNumTextField.text ?? ""),
                      "id": id,
                      ] as? [String : Any]

    let url = URL(string: "https://dev.emi.com/webservice/emi/getassment_details")
    var req =  URLRequest(url: url!)
    req.httpMethod = "POST"
    req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
    req.addValue("application/json", forHTTPHeaderField: "Accept")

    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
    req.httpBody = httpBody

    let session = URLSession.shared

    session.dataTask(with: req, completionHandler: {(data, response, error) in
        if let response = response {
            // print(response)
        }
        if let data = data {

            do{
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                print("the json for make payment \(json)")

                let loanDetails = json["loan_details"] as! [String : Any]
                let dueAmount = loanDetails["emi_amount"] as? String

                    DispatchQueue.main.async {

                        self.dueamountLabel.text = dueAmount

                    }

            }catch{
                print("error")
            }
        }
    }).resume()

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM