简体   繁体   English

如何在Swift中根据JSON ID从collectionView didSelectItemAt indexPath pushViewController(意味着indexPath应该与json id匹配)

[英]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. 我的家庭Viewcontroller包含带有项目的collectionView。 generally when we click on any of item in collection view then we can push to other viewController by using didSelectItemAt indexPath. 通常,当我们单击集合视图中的任何项目时,可以使用didSelectItemAt indexPath推送到其他viewController。 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. 但是在这里,我从Json获取每个项目图像的URL及其ID,并且在每个家庭ID的其他viewController中,我从Json的其他字段获取单独的URL。 when home id and other viewcontroller id matches then i need to push to that viewContoller using didSelectItemAt indexPath in home Viewcontroller. 当家庭ID和其他ViewController ID匹配时,我需要使用家庭Viewcontroller中的didSelectItemAt indexPath推送到该viewContoller。

Here is my code: 这是我的代码:

Home json: 首页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: HomeVC代码:

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: otherVC Json:

for id 2 from home getting below json. 在家中获取ID 2的结果低于json。 for id 45 i am getting another json. 对于ID 45我得到另一个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. 如果家庭ID 2与其他VC ID 2匹配,则需要显示此字段;如果ID 45匹配,则需要显示将很快更新消息以显示。

    {
    "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. 对于每个家庭ID,我都为MakePaymentViewController获得了单独的json。 if we select on 2nd id image from home then need to display those details in MakePaymentViewController. 如果我们从家里选择第二个ID图像,则需要在MakePaymentViewController中显示这些详细信息。 if we select 45 then those details. 如果我们选择45,则这些详细信息。

here if i select any home item i am going to MakePaymentViewController and displaying id 2 details only. 在这里,如果我选择任何家庭用品,我将进入MakePaymentViewController并仅显示id 2详细信息。 but i want individual details according to ids. 但我想要根据ID的个人详细信息。

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. 在按下第二个Controller的同时,根据所选单元格设置id的值。

    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. 将Id的值传递给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()

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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