idkwat2do idkwat2do - 1 month ago 11
Swift Question

How to add json data to array or similar using Swift

I am fairly new to Swift and I am having a few issues with getting understanding how to do what I want to do.

I am currently testing some stuff with json.
What I am trying to do is to append the data I get from my json data into an array. And when my array contains the data I wish to present it to my UICollectionView. I am assuming that I should be using an array.

import UIKit
import Foundation

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

func getData() {
let path = "http://myurl/test.json"
let url = URL(string: path)
let session = URLSession.shared
let task = session.dataTask(with: url!) { (data: Data?, response: URLResponse?, error: Error?) in

let json = JSON(data: data!)
for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! {

let punkter = result["punkt"].string!
print("punkt: \(punkt)")

let rubrik = result["rubrik"].string
print("rubrik: \(rubrik)")

let forslag = result["forslag"].string
print("förslag: \(forslag)")


}
}
task.resume()
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell

cell.customLabel.text = //Put the data form rubrik variable
cell.customTW.text = //Put the data from foreleg variable

return cell

}
}


the function
getData()
gets the correct json data I just need help understanding how to put this data to an array.
(Also, I know I probably shouldn't be getting the data in the ViewController, but this is only a test.)

import Foundation

class Information: NSObject {

var punkter: String?
var rubrik: String?
var forslag: String?

}


I'm thinking that maybe I should be using an array that looks something like this:
var someArray = [Information]()

But I do not know how to then use my
getData()

Or maybe I should be using three different arrays, one for each of my json variables.

Answer

Since you're still using a custom class (well done!, three different arrays are horrible) it's correct to declare a data source array like you suggested

var someArray = [Information]()

Most likely a struct is sufficient, I recommend to use non-optional strings

struct Information {
    var punkter : String
    var rubrik : String
    var forslag : String
}

If the properties won't change you could even use let to make the properties constants.

To populate the array use the nil coalescing operator to check for nil,create the Information instance with the memberwise initializer and append the instance to the datasource array. Then reload the collection view on the main thread.

...
for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! {

  let punkter = result["punkt"].string ?? ""
  let rubrik = result["rubrik"].string ?? ""
  let forslag = result["forslag"].string ?? ""
  let information = Information(punkter:punkter, rubrik:rubrik, forslag:forslag)
  self.someArray.append(information)

}
DispatchQueue.main.async {
   self.collectionView.reloadData()
}
...

Edit:

To display the data in cellForItemAtIndexPath use

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell

    let information = someArray[indexPath.row]
    cell.customLabel.text = information.rubrik
    cell.customTW.text = information.foreleg
    return cell
}