How can I Retrieve a property value from child array object?

故事扮演 提交于 2019-12-25 00:00:46

问题


I'm trying to call an object property from a child array. In the viewcontroller the categories and subcategories are loaded with name, path and images. A new class created for sub-categories able to get name and path but can't retreive the image. The Parent categories are returning all the info including icons however the sub-categories not able to get the image.

ViewController.swift segue prepare.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier! == "catalogproduct") {
        let viewController:CatalogProduct = segue.destination as UIViewController as! CatalogProduct
        viewController.productImageUrl = self.imageUrl
        viewController.productId = self.productId
        viewController.productName = self.productName
        viewController.productPrice = ""

    }
    if (segue.identifier! == "productcategory") {
        let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
        viewController.categoryId = categoryId
        viewController.categoryName = categoryName;
        viewController.categoryType = categoryType;
    }else if (segue.identifier! == "search") {
        let viewController:SearchSuggestion = segue.destination as UIViewController as! SearchSuggestion
        viewController.isHome = true;
    }else if (segue.identifier == "subcategory") {
        let viewController:subCategory = segue.destination as UIViewController as! subCategory
        viewController.subName = categoryName
        viewController.subId = categoryId
        viewController.subCategoryData = subCategory
    }
}

The category section getting all info

import UIKit

class CategoriesController: UIViewController,UITableViewDelegate, UITableViewDataSource {
var cataegoriesCollectionModel = [Categories]()
@IBOutlet weak var categoriesTableView: UITableView!
var arrayForBool :NSMutableArray = [];
var categoryName:String = ""
var categoryId:String = ""
var categoryDict :NSDictionary = [:]
var subCategory:NSArray = []
var subId:String = ""
var subName:String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        //self.navigationItem.title = NetworkManager.sharedInstance.language(key: "Categories")

        let image = UIImage(named: "logo.png")
        navigationItem.titleView = UIImageView(image: image)

        let paymentViewNavigationController = self.tabBarController?.viewControllers?[0]
        let nav1 = paymentViewNavigationController as! UINavigationController;
        let paymentMethodViewController = nav1.viewControllers[0] as! ViewController
        cataegoriesCollectionModel = paymentMethodViewController.homeViewModel.cataegoriesCollectionModel
        categoriesTableView.register(UINib(nibName: "CategoriesTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        self.categoriesTableView.separatorStyle = .none
        categoriesTableView.delegate = self;
        categoriesTableView.dataSource = self;
        categoriesTableView.separatorColor = UIColor.clear
    }


    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 0
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_WIDTH / 2;
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.backgroundColor = UIColor.white
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cataegoriesCollectionModel.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        categoriesTableView.register(UINib(nibName: "CategoryCellTableViewCell", bundle: nil), forCellReuseIdentifier: "CategoryCellTableViewCell")
         let cell:CategoriesTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CategoriesTableViewCell
        cell.backgroundImageView.image = UIImage(named: "ic_placeholder.png")
        NetworkManager.sharedInstance.getImageFromUrl(imageUrl:cataegoriesCollectionModel[indexPath.row].thumbnail , imageView: cell.backgroundImageView)
        cell.categoryName.text = cataegoriesCollectionModel[indexPath.row].name

        cell.selectionStyle = .none
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let childrenArray = cataegoriesCollectionModel[indexPath.row].children! as NSArray;
        if childrenArray.count > 0{
            subId = cataegoriesCollectionModel[indexPath.row].id
            subName = cataegoriesCollectionModel[indexPath.row].name
            subCategory = childrenArray
            self.performSegue(withIdentifier: "subcategory", sender: self)
        }
        else{
            categoryId = cataegoriesCollectionModel[indexPath.row].id
            categoryName = cataegoriesCollectionModel[indexPath.row].name
            self.performSegue(withIdentifier: "productCategorySegue", sender: self)
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "productCategorySegue") {
            let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
            viewController.categoryType = ""
            viewController.categoryName = self.categoryName
            viewController.categoryId = self.categoryId
        }else if (segue.identifier == "subcategory") {
            let viewController:subCategory = segue.destination as UIViewController as! subCategory
            viewController.subName = subName
            viewController.subId = subId
            viewController.subCategoryData = subCategory

        }
    }

}

Subcategory class:

import UIKit


class subCategory: UIViewController,UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource {

    var cataegoriesCollectionModel = [Categories]()
    public  var subCategoryData :NSArray = []
    public var categoryName = " "
    var subCategoryMenuData:NSMutableArray = []
    var categoryId:String = " ";
    var subId:String = ""
    var subName:String = ""

    @IBOutlet weak var subCategoryTable: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = NetworkManager.sharedInstance.language(key: "Categories")
        self.navigationController!.isNavigationBarHidden = false

        subCategoryTable.backgroundColor = UIColor().HexToColor(hexString: GREYBLACK)

        let paymentViewNavigationController = self.tabBarController?.viewControllers?[0]
        let nav1 = paymentViewNavigationController as! UINavigationController;
        let paymentMethodViewController = nav1.viewControllers[0] as! ViewController
                cataegoriesCollectionModel = paymentMethodViewController.homeViewModel.cataegoriesCollectionModel

        let childArray : NSArray? = subCategoryData
        if let itemsArray = childArray{
            for (item) in itemsArray{
                let childStoreData:NSDictionary = item as! NSDictionary;
                self.subCategoryMenuData.add(childStoreData["name"] as? String! ?? "empty");
            }
        }

        subCategoryTable.register(UINib(nibName: "subCategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "listcollectionview")

        subCategoryTable.delegate = self
        subCategoryTable.dataSource = self

        print(subCategoryData)

    }


    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ view: UICollectionView, heightForHeaderInSection section: Int) -> CGFloat{
        return 0
    }

    func collectionView(_ view: UICollectionView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_WIDTH / 4;
    }

    func collectionView(_ view: UICollectionView, willDisplay cell: UICollectionView, forRowAt indexPath: IndexPath) {
        cell.backgroundColor = UIColor.white
    }

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


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        subCategoryTable.register(UINib(nibName: "subCategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "listcollectionview")

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listcollectionview", for: indexPath) as! subCategoryCollectionViewCell
        cell.backgroundImageView.image = UIImage(named: "ic_placeholder.png")
        NetworkManager.sharedInstance.getImageFromUrl(imageUrl:cataegoriesCollectionModel[indexPath.row].thumbnail , imageView: cell.backgroundImageView)
        cell.categoryName.text = (subCategoryMenuData [indexPath.row] as? String)
        cell.categoryName?.textColor = UIColor().HexToColor(hexString: REDCOLOR)

        return cell;
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let childDict: NSDictionary = subCategoryData .object(at: indexPath.row) as! NSDictionary

        if (childDict.object(forKey: "children") as! NSArray).count > 0{
            let sb = UIStoryboard(name: "Main", bundle: nil)
            let initViewController: subCategory? = (sb.instantiateViewController(withIdentifier: "subCategory") as? subCategory)
            initViewController?.subCategoryData = (childDict.object(forKey: "children") as! NSArray)
            initViewController?.subName = childDict.object(forKey: "name") as! String!
            initViewController?.subId = childDict.object(forKey: "path") as! String!
            initViewController?.modalTransitionStyle = .flipHorizontal
            self.navigationController?.pushViewController(initViewController!, animated: true)
        }else{

            categoryName = childDict .object(forKey: "name") as! String
            categoryId = childDict .object(forKey: "path") as! String
            self.performSegue(withIdentifier: "productCategorySegue", sender: self)
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "productCategorySegue") {
            let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
            viewController.categoryType = ""
            viewController.categoryName = self.categoryName
            viewController.categoryId = self.categoryId
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navigationItem.title = categoryName;
        self.navigationController!.isNavigationBarHidden = false

    }

}

The JSON response printed:

  categories =     (
                {
            children =             (
                                {
                    children =                     (
                                                {
                            children =                             (
                            );
                            column = 1;
                            icon = "https://example.com/image/cache/placeholder-150x150_0.png";
                            image = "https://example.com/image/categories/1.jpg";
                            name = "Subcat Name";
                            path = 1197;
                            thumb = "https://example.com/image/categories/1.jpg";
                        },

Any help please how to retrieve the image for subcategory, thanks in advanced!


回答1:


A quick solution would be to pass the image url string "https://example.com/image/categories/1.jpg" into a function that returns an image:

Synchronously

func imageFromURL(_ urlStr: String) -> UIImage? {
  guard 
        let url = URL(string: urlStr), 
        let data = try? Data(contentsOfUrl:url),
        let image = UIImage(data: data) 
        else {return nil}

  return image
}

aSynchronously

extension UIImageView {
   func loadImageFrom(urlString: String, mode: UIViewContentMode) {
    guard let url = URL(string: urlString) else {return}

    self.contentMode = mode

    URLSession.shared.dataTask(with: url) { data, response, error in
        guard
            error == nil,
            let httpURLResponse = response as? HTTPURLResponse, 
            httpURLResponse.statusCode == 200,
            let data = data, 
            let image = UIImage(data: data)
        else { 
            return print(error?.localizedDescription ?? "Something went wrong when loading the image")
        }
        DispatchQueue.main.async { 
            self.image = image
        }
    }
    .resume()
  }
}

Use

 imageView.loadImageFrom(urlString:"https://example.com/image/categories/1.jpg", mode: .scaleAspectFit)

-

See link for more details:

Loading Image From URL



来源:https://stackoverflow.com/questions/51662511/how-can-i-retrieve-a-property-value-from-child-array-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!