我有一个集合视图,只能显示类别名称及其图像。我通过做一些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)
}
}
}
并形成我上面的代码,你可以看到,我已经完成了另一个视图控制器的segue。我将ID
传递给另一个视图控制器。在另一个视图控制器中,我需要显示用户在第一个视图控制器中选择的产品项。
在我的第二个视图控制器中,我已经做了一些api来显示所有产品。所以流程是:
当用户在我的第一个视图控制器中按任何类别名称时,它必须转到第二个视图控制器,并且应该是所选类别名称的特定产品。这是我的第二个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,并且我将与所有产品api调用类别ID进行比较。我需要单独展示那个特定的产品。怎么做?
if(bId == self.BTypeId)
请帮帮我。
由于
答案 0 :(得分:1)
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
}
您的输出:
您的问题解决了批准答案并放弃投票谢谢。 快乐的编码。