0

I am grabbing data from a url which is a PHP script that is JSON encoding my data from a MySQL database. My data is coming into my app and I know how to parse it but I am unsure how to place my data inside of each item's textField.stringvalue in my Collection View. Most of the information I have found on this subject is all for iOS and I am making an app for OS X.

ViewController.swift

import Cocoa

class ViewController: NSViewController  {

@IBOutlet weak var collectionView: NSCollectionView!

var productCategories: [ProductCategory]?

let baseURL = "http://myURL"

override func viewDidLoad() {
    super.viewDidLoad()

    getJSON()
    self.collectionView.reloadData()

}

func getJSON(){

    let url = NSURL(string: baseURL)
    let request = NSURLRequest(url: url! as URL)
    let session = URLSession(configuration: URLSessionConfiguration.default)
    let task = session.dataTask(with: request as URLRequest) { (data,response,error) -> Void in

        if error == nil {

            let swiftyJSON = JSON(data:data!)
            print(swiftyJSON)
            let product = swiftyJSON[].arrayValue

            for name in product{

                let names = name["product_name"].stringValue
               print(names)
            }


        } else{
            print("Error")
        }
    }
    task.resume()
}


override var representedObject: Any? {
    didSet {
    // Update the view, if already loaded.
    }
}


}

extension ViewController: NSCollectionViewDataSource{

func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
    if let count = productCategories?.count {
        return count
    }
    return 0
}

func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {



    let item = collectionView.makeItem(withIdentifier: "ImageCollectionViewItem", for: indexPath)

    item.textField?.stringValue = Product.product_name

    return item
}
}

Model.swift

import Foundation

class ProductCategory: NSObject {

var name: String?
var productss: [Product]?
var type: String?
}



class Product: NSObject {

var id: NSNumber?
var product_name: String?
var product_price: NSNumber?
var product_description: String?
var product_image: String?
var product_download: String?
var product_video: String?
var product_featured: Int?
}
  • Once again, your naming (plural - multiple items `product` and singular - one item `names`) is very confusing – vadian Sep 30 '16 at 16:15
  • I have figured out that I can assign my product_name to an item like this: ' let productName = Product().product_name item.textField?.stringValue = productName! ' But I still do not know how to make them show in my collectionView. When i run my app the window is blank. – Nick Balistreri Sep 30 '16 at 19:26

0 Answers0