I am pulling in JSON data from a url and displaying my data in labels in a .xib. The .xib is being called as a NSCollectionViewItem via the identifier "test". Instead of each of my items being displayed it is only showing the last element of the array. Any help would be greatly appreciated.
ViewController.swift
import Cocoa
class ViewController: NSViewController {
var products: [Product]?
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: Any? {
didSet {
/
}
}
}
extension ViewController: NSCollectionViewDataSource {
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = products?.count {
return count
}
return 3
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "test", for: indexPath)
return item
}
}
test.swift
import Cocoa
class test: NSCollectionViewItem {
@IBOutlet weak var label: NSTextField!
@IBOutlet weak var label2: NSTextField!
var names: [String] = []
var prices: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
/
let requestURL: NSURL = NSURL(string: "http:/
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)
if let products = json as? [[String: Any]] {
for product in products {
if let name = product["product_name"] as? String {
if let price = product["product_price"] as? String {
self.names.append(name as String)
self.prices.append(price as String)
DispatchQueue.main.async() {
for (index, _) in self.names.enumerated() {
self.label.stringValue = self.names[index]
}
for (index, _) in self.prices.enumerated() {
self.label2.stringValue = self.prices[index]
}
}
print(name,price)
}
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
}
class Product: NSObject {
var id: NSNumber?
var product_name: String?
var product_price: String?
}