我有一个快速的项目,我使用Alamofire和swiftyJson来进行API调用,并返回一堆JSON值。我有一个类别和一个产品Model类,它们被传递给TableViewController,一切都很好。我将选定的类别ID和SLUG存储在变量中。我现在面临的问题是如何将与所选类别相关联的产品传递给productsTableViewController。所选类别JSON看起来像这样
[
{
"url": "http://127.0.0.1:8000/api/products/13/",
"id": 13,
"title": "ada",
"description": "how all this",
"structure": "standalone",
"date_created": "2018-05-13T17:41:59.935158Z",
"date_updated": "2018-05-26T17:25:19.024144Z",
"recommended_products": [],
"attributes": [
{
"name": "Gender",
"value": "Male"
}
],
"categories": [
"Clothes"
],
"images": [
{
"id": 11,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f4.jpg",
"caption": "",
"display_order": 3,
"date_created": "2018-05-26T17:25:19.155159Z",
"product": 13
}
],
},
我选择的类别为
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let category = CategoryServices.instance.categories[indexPath.row]
CategoryServices.instance.selectedCategory = category
print(category)
let index = IndexPath(row: indexPath.row, section: 0)
tableView.reloadRows(at: [index], with: .none)
tableView.selectRow(at: index, animated: false, scrollPosition: .none)
NotificationCenter.default.post(name: NOTIFY_CATEGORY_SELECTED, object: nil)
//pull revel back on selected
self.revealViewController().revealToggle(animated: true)
}
我有我的默认产品显示,即所有产品
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: PRODUCT_CELL, for: indexPath) as? ProductsCell {
let product = ProductServices.instance.products[indexPath.row]
cell.configureCell(product: product)
return cell
} else {
return UITableViewCell()
}
}
产品细胞
func configureCell(product: Products) -> Void {
productPriceLabel.text = product.productPrice
producNameBtn.setTitle(product.productTitle, for: .normal)
if (product.productImg.count > 0 ) {
productImg.sd_setImage(with: URL(string: product.productImg[0]) )
} else {
productImg.image = UIImage(named: "image_not_found")
}
categorySercices.swift
func findProductsForCategory(categorySlug: String, categoryId: Int, completion: @escaping CompletionHandler) -> Void {
Alamofire.request("\(URL_CATEGORY_PRODUCT)\(categorySlug)_\(categoryId)", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
print("URL_CATEGORY_PRODUCT \(URL_CATEGORY_PRODUCT)")
if response.result.error == nil {
guard let data = response.data else {return}
do {
if let json = try JSON(data: data).array {
for item in json {
let url = item["url"].stringValue
let id = item["id"].intValue
let title = item["title"].stringValue
let imagesList = item["images"].arrayValue
let imagesURL = imagesList.map {$0["original"].stringValue}
let currency = item["price"]["currency"].stringValue
let price = item["price"]["excl_tax"].stringValue
let product = Products(productUrl: url, id: id, productTitle: title, productImg: imagesURL, productPrice: "\(currency) \(price)")
self.products.append(product)
}
completion(true)
}
} catch {
print("eroorrrre")
}
} else {
debugPrint(response.result.error as Any)
completion(false)
}
}
}
ProductServices.swift
class ProductServices {
//MARK :- SINGLETONS & VARIABLES
static let instance = ProductServices()
var products = [Products]()
var productDetails = [ProductDetail]()
var availability = [Availability]()
var price = [Price]()
var selectedProduct : Products?
var selectedCategory : Categories?
//MARK :- ALL PRODUCTS
func findAllProducts(completion: @escaping CompletionHandler) -> Void {
Alamofire.request(URL_PRODUCTS, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
if response.result.error == nil {
guard let data = response.data else {return}
do {
if let json = try JSON(data: data).array {
for item in json {
let url = item["url"].stringValue
let id = item["id"].intValue
let title = item["title"].stringValue
let imagesList = item["images"].arrayValue
let imagesURL = imagesList.map {$0["original"].stringValue}
let currency = item["price"]["currency"].stringValue
let price = item["price"]["excl_tax"].stringValue
let product = Products(productUrl: url, id: id, productTitle: title, productImg: imagesURL, productPrice: "\(currency) \(price)")
self.products.append(product)
}
completion(true)
for i in [self.products[0].productImg] {
}
}
}catch {
print("error")
}
} else {
debugPrint(response.result.error as Any)
completion(false)
}
}
}
//MARK :- PRODUCT DETAILS
func findIndividualProducts(id: Int, completion: @escaping CompletionHandler) -> Void {
Alamofire.request("\(URL_PRODUCT_DETAIL)\(id)", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
if response.result.error == nil {
do {
if let data = response.result.value {
let item = JSON(data)
let url = item["url"].stringValue
let id = item["id"].intValue
let title = item["title"].stringValue
let description = item["description"].stringValue
let recommendedProducts = item["recommended_products"].stringValue
let attributes = item["attributes"].arrayValue
let categories = item["categories"].arrayValue
let productClass = item["product_class"].stringValue
let imagesList = item["images"].arrayValue
let imagesURL = imagesList.map {$0["original"].stringValue}
let options = item["options"].stringValue
let children = item["children"].stringValue
let productDetail = ProductDetail(productUrl: url, id: id, productTitle: title, productDescription: description, recommendedProducts: recommendedProducts, attributes: attributes, categories: categories, productClass: productClass, productImg: imagesURL, options: options, children: children)
self.productDetails.append(productDetail)
completion(true)
}
} catch {
}
} else {
}
}
}
}
ProductCell.swift
class ProductsCell: UITableViewCell {
@IBOutlet weak var productImg: UIImageView!
@IBOutlet weak var productStatusLabel: UILabel!
@IBOutlet weak var productPriceLabel: UILabel!
@IBOutlet weak var producNameBtn: UIButton!
@IBOutlet weak var productSectionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell(product: Products) -> Void {
productPriceLabel.text = product.productPrice
producNameBtn.setTitle(product.productTitle, for: .normal)
if (product.productImg.count > 0 ) {
productImg.sd_setImage(with: URL(string: product.productImg[0]) )
} else {
productImg.image = UIImage(named: "image_not_found")
}
}
将在requestswi上提供更多代码