簡體   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

我的家庭Viewcontroller包含帶有項目的collectionView。 通常,當我們單擊集合視圖中的任何項目時,可以使用didSelectItemAt indexPath推送到其他viewController。 但是在這里,我從Json獲取每個項目圖像的URL及其ID,並且在每個家庭ID的其他viewController中,我從Json的其他字段獲取單獨的URL。 當家庭ID和其他ViewController ID匹配時,我需要使用家庭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()
}

}

otherVC Json:

在家中獲取ID 2的結果低於json。 對於ID 45我得到另一個JSON。 如果家庭ID 2與其他VC 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詳細信息。 但我想要根據ID的個人詳細信息。

請幫助我的代碼。

在第二個控制器上創建變量

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM