Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How do I get collectionView to read my data response and count the array in another function swift?

`// // ViewController.swift // Fashun // // Created by Alex Macleod on 20/10/14. // Copyright (c) 2014 Alex Macleod. All rights reserved. //

import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

var collectionView: UICollectionView?

var instanceOfCustomObject: CustomObject = CustomObject()

var accessToken: NSString!
var userDefaults: NSUserDefaults!

// private let api = "d4984c8cfa78689bd066d82bec820fd5"

override func viewDidLoad() {
    super.viewDidLoad()

    userDefaults = NSUserDefaults.standardUserDefaults()
    self.accessToken = userDefaults!.objectForKey("accessToken") as NSString
    //        instanceOfCustomObject.someProperty = "Hello World"

// var accessToken : NSString? = NSString(instanceOfCustomObject.accessToken) // println(accessToken) // instanceOfCustomObject.authorize()

    // Do any additional setup after loading the view, typically from a nib.
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
    layout.itemSize = CGSize(width: 124, height: 124)
    layout.minimumInteritemSpacing = 1.0
    layout.minimumLineSpacing = 1.0
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView!.dataSource = self
    collectionView!.delegate = self
    collectionView!.registerClass(Cell.self, forCellWithReuseIdentifier: "Cell")
    collectionView!.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(collectionView!)

    getData()

}

func getData() -> Void {
    let baseUrl = NSURL(string:"https://api.instagram.com/v1/users/3/media/recent/?access_token=\(self.accessToken)")

    let forcastUrl = NSURL(string: "", relativeToURL: baseUrl)

    //        let data = NSData(contentsOfURL: forcastUrl)
    //        println(data)
    let sharedSession = NSURLSession.sharedSession()
    let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(baseUrl, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in


        //            var urlContents = NSString.stringWithContentsOfURL(location, encoding: NSUTF8StringEncoding, error: nil)
        //            println(urlContents)

        let dataObject = NSData(contentsOfURL: baseUrl)

        if (error == nil) {
            let responseDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject, options: nil, error: nil) as NSDictionary

// println("Response:(responseDictionary)") // let currentResponse = Parse(responseDictionary: responseDictionary)

            var photos = responseDictionary.valueForKeyPath("data.images.standard_resolution.url") as NSArray
            println(photos)
            //                photoCount = self.photos!.count as Int

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                //                    self.temperatureLabel.text = "\(currentWeather.temperature)"
                //                    self.iconView.image = currentWeather.icon!
                //                    self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
                //                    self.humidityLabel.text = "\(currentWeather.humidity)"
                //                    self.percipitationLabel.text = "\(currentWeather.precipProbability)"
                //                    self.summeryLabel.text = "\(currentWeather.summary)"
                //
                //                    self.refreshActivityIndicator.stopAnimating()
                //                    self.refreshActivityIndicator.hidden = true
                //
                //                    self.refreshButton.hidden = false
            })

        } else {

            let networkIssueController = UIAlertController(title: "Error", message: "I got 99 problems but a bitch ain't one", preferredStyle: .ActionSheet)
            let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
            networkIssueController.addAction(okButton)
            let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
            networkIssueController.addAction(cancelButton)

            self.presentViewController(networkIssueController, animated: true, completion: nil)

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                //Stop refresh animation
                //                    self.refreshActivityIndicator.stopAnimating()
                //                    self.refreshActivityIndicator.hidden = true
                //                    self.refreshButton.hidden = false

            })
        }
    })

    downloadTask.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



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

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as Cell
    cell.textLabel.text = "Text"
    cell.imageView.image = UIImage(named: "star")
    return cell
}

} `

trying to count the number of urls I receive from the responseDictionary in my collection view. I have been struggling with this for ages and I'm going crazy please help. I also tried creating a new class but I failed at that

1 Answer

https://www.dropbox.com/s/t82qcgw7lcde7tx/Fashun.zip?dl=0

Heres a link to the project. Trying to rebuild the photobombers app in swift! please help!