![](/img/trans.png)
[英]Swift: how to call json id from UIButton CollectionView cell
[英]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.