json - 如何在Swift中根据json id从collectionView didSelectItemAt indexPath推送ViewController(意味着indexPath应该与json id匹配)

标签 json swift uicollectionview pushviewcontroller didselectrowatindexpath

我的主视图 Controller 包含带有项目的collectionView。通常,当我们单击 Collection View 中的任何项目时,我们可以使用 didSelectItemAt indexPath 推送到其他 View Controller 。但在这里我从 Json 中获取每个项目图像 url 及其 id,在其他 viewController 中,对于每个家庭 id,我从 Json 中获取带有其他字段的单独 url。当 home id 和其他 viewcontroller id 匹配时,我需要使用 home Viewcontroller 中的 didSelectItemAt indexPath 推送到该 viewContoller。

这是我的代码:

主页 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代码:

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()
}

}

其他VC Json:

来自家的 id 2 低于 json。对于 id 45,我得到另一个 json。如果家庭 id 2 和其他 vcs id 2 匹配,则需要显示此字段;如果 id 45 匹配,则需要显示将很快更新的消息。

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

代码;

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()
}

}

对于每个家庭 ID,我都会为 MakePaymentViewController 获取单独的 json。如果我们选择家中的第二个 id 图像,则需要在 MakePaymentViewController 中显示这些详细信息。如果我们选择 45,那么这些详细信息。

在这里,如果我选择任何主页项目,我将转到 MakePaymentViewController 并仅显示 id 2 详细信息。但我想要根据 ids 的个人详细信息。

请帮助我编写代码。

最佳答案

在第二个 Controller 上创建变量

class MakePaymentViewController: UIViewController {
    var id = ""
}

按下第二个 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)

    }

将 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()

}

关于json - 如何在Swift中根据json id从collectionView didSelectItemAt indexPath推送ViewController(意味着indexPath应该与json id匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57963499/

相关文章:

python - 在 Pandas 数据框中展平嵌套的Json

javascript - 使用循环从 javascript 中的对象获取函数结果

ios - 使用多个转场 |如何使用 Cell 数据执行特定的 Segues

ios - 当 extendedLayoutIncludesOpaqueBars 设置为 true 时,UICollectionView 不工作

ios - 在 Collection View 中选择和删除图像

php - 来自 WikiMedia API 的 cURL HTTP 请求不起作用

javascript - 如何使用 Node js中的键对两个数组进行分组

ios - 我们想在我们自己的服务器上使用 Rocket.chat 而不是 open.rocket.chat 一些我们无法继续的事情

ios - 保存后自动打开pdf文件

swift - 用户图像的上下文菜单配置?