gpt4 book ai didi

ios - 将 id 传递到另一个屏幕以显示特定的 id - 产品及其详细信息

转载 作者:行者123 更新时间:2023-11-28 16:06:50 25 4
gpt4 key购买 nike

我有一个 Collection View ,它必须只显示类别名称及其图像。我通过一些 api 调用来显示这个类别名称、图像。而且对于每个类别名称,我将获得每个类别名称的客户 ID。这是完整的代码

 func apicalling () {

let headers = [
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "7adebcbe-18b4-d2a7-2159-2fbcaea27edd"
]
let parameters = [
"customerID": "1",
"listType": "2"
]
do {
let postData = try JSONSerialization.data(withJSONObject: parameters, options :[])
let request = NSMutableURLRequest(url: NSURL(string: "http://example/categoryname.php")! as URL,
cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
///print(error)
} else {

DispatchQueue.main.async(execute: {

if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? Dictionary<String,AnyObject>
{
let status = json["status"] as? Int;
if(status == 1)
{
//print("SUCCESS....")
if let typeValues = json["categories"] as? [NSDictionary]
{
DispatchQueue.main.async(execute: {

// print("INSIDE CATEGORIES")

for item in typeValues
{
// print("INSIDE LISTING ITEMS...")

self.BTdata.append(BTData(json:item))

}

//print(self.BTdata[0].BTNames)


self.collectionView!.reloadData()

})
}

}

}
})

}
})

dataTask.resume()
} catch {
// print("JSON serialization failed: \(error)")
}
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return BTdata.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

cell.CatName.text = BTdata[(indexPath as NSIndexPath).row].BTNames

let imgURL: URL = URL(string: BTdata[(indexPath as NSIndexPath).row].BTImage!)!

let request: URLRequest = URLRequest(url: imgURL)

let session = URLSession.shared

let task = session.dataTask(with: request, completionHandler: {
(data, response, error) -> Void in

if (error == nil && data != nil)
{
func display_image()
{
cell.ProductImg.image = UIImage(data:data!)
}

DispatchQueue.main.sync(execute: display_image)
}
})

task.resume()

return cell
}

func getIndexPathForSelectedCell() -> IndexPath?
{
var indexPath:IndexPath?

if collectionView.indexPathsForSelectedItems!.count > 0 {
indexPath = collectionView.indexPathsForSelectedItems![0]
}
return indexPath
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "showDetails"
{
if let indexPath = getIndexPathForSelectedCell()
{
let ContainerviewController = segue.destination as! DetailVC

ContainerviewController.BTdata = [BTdata[(indexPath as NSIndexPath).row]]

print("Printing value on collection click.....")

print(BTdata[(indexPath as NSIndexPath).row].BTIds)

}
}
}

从我上面的代码中你可以看到,我已经完成了到另一个 View Controller 的转场。我正在将 ID 传递给另一个 View Controller 。在另一个 View Controller 中,我需要显示用户在我的第一个 View Controller 中选择的产品项目。

在我的第二个 View Controller 中,我做了一些 api 来显示所有产品。所以流程是:

  1. 当用户在我的第一个 View Controller 中按下任何类别名称时,它必须转到第二个 View Controller ,并且应该是所选类别名称的特定产品。这是我的第二个 VC 的代码:

    在这里,我从我的第一个 vc 中获取用户单击任何类别名称的 ID:

    override func viewDidLoad() {

    super.viewDidLoad()

    self.BTypeId = BTdata[0].BTIds
    Allproductapicalling ()
    }

    func Allproductapicalling () {

    let headers = [
    "content-type": "application/json",
    "cache-control": "no-cache",
    "postman-token": "c98d0000-637b-1efc-8f93-f9e277ffefcd"
    ]
    let parameters = [
    "customerID": "1",
    "listType": "1"
    ]

    do {
    let postData = try JSONSerialization.data(withJSONObject: parameters, options :[])
    let request = NSMutableURLRequest(url: NSURL(string: "http://exp.php")! as URL,
    cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
    ///print(error)
    } else {

    DispatchQueue.main.async(execute: {

    if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? Dictionary<String,AnyObject>
    {
    let status = json["status"] as? Int;
    if(status == 1)
    {
    print("SUCCESS....")

    if let typeValues = json["products"] as? [NSDictionary]
    {
    DispatchQueue.main.async(execute: {

    print("INSIDE CATEGORIES")

    for item in typeValues {

    let bId = item.value(forKey: "categoryID") as! String

    if(bId == self.BTypeId) {

    self.Productdata.append(ProductData(json:item))

    }
    }

    })

    //print("Product Name : ", self.Productdata[0].proName)
    }

    }

    }
    })

    }
    })

    dataTask.resume()



    } catch {
    // print("JSON serialization failed: \(error)")
    }
    }

我的问题出在 api 调用代码上面的这一行中:

if let typeValues = json["products"] as? [NSDictionary]
{
DispatchQueue.main.async(execute: {
for item in typeValues {
let bId = item.value(forKey: "categoryID") as! String
if(bId == self.BTypeId) {
self.Productdata.append(ProductData(json:item))
}
}

})

我正在从我的第一个 VC 中获取选定的类别 ID,并且我正在与调用类别 ID 的所有产品 API 进行比较。我需要单独展示该特定产品。该怎么做??

if(bId == self.BTypeId)

请帮帮我。

谢谢

最佳答案

 DispatchQueue.main.async(execute: {
for item in typeValues {
let bId = item.value(forKey: "categoryID") as! String
if(bId as? String == self.BTypeId) {
print("Hurray sathish......")
self.Productdata.append(ProductData(json:item))

// print(self.Productdata.append(bId))

}
}
self.Collectionview.delegate = self
self.Collectionview.dataSource = self
self.Collectionview.reloadData()
})

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DetailCollectionviewcell

cell.DetailProductName.text = Productdata[indexPath.row].proDescription

let imgURL: URL = URL(string: Productdata[indexPath.row].proImage!)!

let request: URLRequest = URLRequest(url: imgURL)

let session = URLSession.shared

let task = session.dataTask(with: request, completionHandler: {
(data, response, error) -> Void in

if (error == nil && data != nil)
{
func display_image()
{
cell.DetailImage.image = UIImage(data:data!)
}


DispatchQueue.main.sync(execute: display_image)
}
})

task.resume()


return cell
}

你的输出:

您的问题已解决批准答案并放弃投票谢谢。快乐编码。

关于ios - 将 id 传递到另一个屏幕以显示特定的 id - 产品及其详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com