mack mack - 1 month ago 4
JSON Question

pass id to another screen to display the particular id - product and its details

I have one collection view which have to display only the category name and its image. And i am showing this category name, image by doing some api calling. And also for each category name i will get the customer id for each category name. Here is the full code for that

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)

}
}
}


And form my above code you can see that, i have done the segue to another view controller. And i am passing the
ID
to another view controller.In another view controller, i need to display the product items that user select in my first view controller.

In my second view controller, i have done some api to show all product .So the flow is :


  1. When user press any category name in my first view controller, it have to go to second view controller and should so the particular product for the selected category name. Here is the code of my second VC :

    Here i am getting the id from my first vc that user clicked any category name :

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



My problem is in this line from above api calling code :

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

})


i am getting the selected category id from my first VC, and i am comparing with the all product api calling category id. And i need to display that particular product alone.How to do that ??

if(bId == self.BTypeId)


Please help me out.

Thanks

Answer
 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
    }

Your Output :

Your problem solve approve answer and give up vote thank you. Happy Coding.

Comments