brkr
brkr

Reputation: 1272

How to iterate through Dictionary of Dictionary Values in UITableViewCell?

This is my first post and I hope its a great question because iv been stuck on this for days. (Literally searched every related question and found nothing that I could add up for a solution.)

Basically I'm building a pure Swift application. My problem is that I cant figure out how to place each dictionary values into each UITableCell that is created.

Also the JSON response from the GET creates a NSCFDictionary type.

UITableViewCell Properties

So basically I need to store each offer object's (name, description, thumb_url) in every UITableViewCell that the ViewController creates.

GET Request

import UIKit

class freeIAPCell: UITableViewCell {

    @IBOutlet weak var aName: UILabel!

    @IBOutlet weak var aDescription: UILabel!

    @IBOutlet weak var aImage: UIImageView!



}

class FreeIAPViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    // Everbadge Request

    var apiURL = "apiurlhere"

    var parsedArray: [[String:String]] = []

    func queryEB() {

        // Query  DB Here

        // Store the API url in a NSURL Object
        let nsURL = NSURL(string: apiURL)

        let request = NSMutableURLRequest(URL: nsURL!)

        request.HTTPMethod = "GET"

        // Execute HTTP Request

        let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
            data, response, error in

            if error != nil {
                print("Error = \(error)")
                return
            }

            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary

                print(json.isKindOfClass(NSDictionary)) // true

                let data = json.objectForKey("data") as! NSDictionary
                //print(data)
                let m = data.objectForKey("offers") as! NSArray
                print(m)
                print(m.valueForKeyPath("name"))
                self.parsedArray = m as! [[String : String]]


            } catch {
                print("THERE WAS AN ERROR PARSING JSON FOR EVERBADGE")
            }


        }
        task.resume()

    }


    override func viewDidLoad() {
        super.viewDidLoad()
        queryEB()




    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)


    }

    // MARK: UITableView method implementation

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


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("freeAppCell", forIndexPath: indexPath) as! freeIAPCell

        let obj = parsedArray[indexPath.row] // fatal error: Index out of range
        cell.aName.text = obj["name"]
        return cell
    }


}

API Request Data Structure (print(m))

( 
              {
                "name" = "Mate";
                id = 23941;
                description = "10-20 word description goes here"
                "url" = "google.com
                "ver" = "0.12"
                price = "0.17"
                "public_name" = "Good Ole Mate"
                "thumb_url" = "http://google.com/mate.jpg
          };
           {
                "name" = "Mate";
                id = 23941;
                description = "10-20 word description goes here"
                "url" = "google.com
                "ver" = "0.12"
                price = "0.17"
                "public_name" = "Good Ole Mate"
                "thumb_url" = "http://google.com/mate.jpg
          };
          {
                "name" = "Mate";
                id = 23941;
                description = "10-20 word description goes here"
                "url" = "google.com
                "ver" = "0.12"
                price = "0.17"
                "public_name" = "Good Ole Mate"
                "thumb_url" = "http://google.com/mate.jpg
          };
           {
                "name" = "Mate";
                id = 23941;
                description = "10-20 word description goes here"
                "url" = "google.com
                "ver" = "0.12"
                price = "0.17"
                "public_name" = "Good Ole Mate"
                "thumb_url" = "http://google.com/mate.jpg
          };
           {
                "name" = "Mate";
                id = 23941;
                description = "10-20 word description goes here"
                "url" = "google.com
                "ver" = "0.12"
                price = "0.17"
                "public_name" = "Good Ole Mate"
                "thumb_url" = "http://google.com/mate.jpg
          };
);

Upvotes: 1

Views: 915

Answers (1)

Charles Jr
Charles Jr

Reputation: 9139

First create public arrays for your 3 items...

var nameArray = [String]()
var descriptionArray = [String]()
var thumbnailArray = [String]()

Then loop through your json parse like this....

 let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! NSDictionary
    if responseString != nil
    {
        let items: AnyObject! = responseString["items"] as AnyObject!
        if items != nil
        {
            // Loop through all search results and keep just the necessary data.
            for var i=0; i<items.count; ++i
            {

                if let names = items[i]["name"] as? NSDictionary
                {
                    let name = names as! String
                    self.nameArray.append(name)
                }
                if let descriptions = items[i]["description"] as? NSDictionary
                {
                    let description = descriptions as! String
                    self.descriptionArray.append(description)
                }
                if let thumbnails = items[i]["thumb_url"] as? NSDictionary
                {
                    let thumbnail = thumbnails as! String
                    self.thumbnailArray.append(thumbnail)
                }
            }
        }
        self.resultsTableView.reloadData()

Create an OfferTableViewCell Class with a nameLabel:UILabel, descriptionLabel:UILabel, and thumbnailImage:UIImage. Finally in your cellForRowAtIndexPath.....

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("offer", forIndexPath: indexPath) as! OfferTableViewCell
        cell.nameLabel.text = self.nameArray[indexPath.row]
        cell.descriptionLabel.text = self.descriptionArray[indexPath.row]
        let url = NSURL(string: self.thumbnailArray[indexPath.row])
        let data = NSData(contentsOfURL: url!)
        cell.thumbnailImage.image = UIImage(data: data!)

        return cell

    }

Upvotes: 1

Related Questions