How to pass data from variable to an Array? - ios

In my app i load from database guest's informations.
After checked user profile, i pass all data by using global variables and by sender.
in my tableview i have to display data from variables... the problem is that i cannot put variables to array, so i tried to implement a struct method, but it doesn't works.
//
// SchedaVolontario.swift
// Amesci
//
// Created by Gianluca Caliendo on 06/07/17.
// Copyright © 2017 Amesci. All rights reserved.
//
import UIKit
class SchedaVolontario: UIViewController, UITableViewDataSource, UITableViewDelegate {
var cognome : String?
var sede : String?
var progetto : String?
var datainizioservizio : String?
var datafineservizio : String?
var licenze : String?
var malattie : String?
var CodvolontarioString : String?
struct nomestruct {
var nome : String?
}
struct cognomestruct {
var cognome : String?
}
struct sedestruct {
var sede : String?
}
struct progettostruct {
var progetto : String?
}
struct datainizioserviziostruct {
var datainizioservizio : String?
}
struct datafineserviziostruct {
var datafineservizio : String?
}
struct licenzestruct {
var licenze : String?
}
struct malattiestruct {
var malattie : String?
}
struct codvolontariostruct {
var CodvolontarioString : String?
}
var list = [nomestruct.self, cognomestruct.self, sedestruct.self, progettostruct.self, datainizioserviziostruct.self, datafineserviziostruct.self, licenzestruct.self, malattiestruct.self, codvolontariostruct.self] as [Any]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = list[indexPath.row] as? String
return cell
}
override var prefersStatusBarHidden : Bool {
return true
}
}

It didn't work because you populate a list of types, not values. You should include a reference to your tableView and reload it everytime you populate your list. Try this:
import UIKit
class SchedaVolontario: UIViewController, UITableViewDataSource, UITableViewDelegate {
var nome: String?
var cognome : String?
var sede : String?
var progetto : String?
var datainizioservizio : String?
var datafineservizio : String?
var licenze : String?
var malattie : String?
var codvolontarioString : String?
var guestInfoList: [String] = []
// Connect this outlet to your table view in storyboard
#IBOutlet weak var guestInfoTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
populateGuestInfoList()
guestInfoTableView.reloadData()
}
func populateGuestInfoList() {
if let nome = nome {
guestInfoList.append(nome)
}
if let cognome = cognome {
guestInfoList.append(cognome)
}
if let sede = sede {
guestInfoList.append(sede)
}
if let progetto = progetto {
guestInfoList.append(progetto)
}
if let datainizioservizio = datainizioservizio {
guestInfoList.append(datainizioservizio)
}
if let datafineservizio = datafineservizio {
guestInfoList.append(datafineservizio)
}
if let licenze = licenze {
guestInfoList.append(licenze)
}
if let malattie = malattie {
guestInfoList.append(malattie)
}
if let codvolontarioString = codvolontarioString {
guestInfoList.append(codvolontarioString)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return guestInfoList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = guestInfoList[indexPath.row]
return cell
}
}

Yes, you can put variables into an array. The easiest thing is for them to be a common type. For example:
var list = [nomestruct.nome!, cognomestruct.cognome!, sedestruct.sede!, progettostruct.progretto!, datainizioserviziostruct.datainizioservizio!, datafineserviziostruct.datafineservizio!, licenzestruct.licenze!, malattiestruct.malattie!, codvolontariostruct.codvolontarioString!] as [String]
Judging from the initial declarations (which are not structs), you could also do:
var list = [self.sede!,self.progretto!, self.datainizioservizio!, self.datafineservizio!, self.licenze!, self.malattie!, self.codvolontarioString!] as [String]
This is not very optimal code though, because A) I don't know where or when you are actually setting those structure values and B) I am dereferencing optional strings and if the string is set to nil, your code will crash when it tries to access that string.
I wouldn't use structs for this unless you wanted to add extra data or properties to the structs that you want to reference again later on.
You should edit your question to show when you populate the structures with data and how you do it.

here I had done Code to add objects using struct and passing direct String values to a array of string , Have a look and tell me if you face any problem with it
1) here its written code
//using direct string values
var cognome : String?
var sede : String?
var progetto : String?
cognome = "1"
sede = "2"
progetto = "3"
var listt = [String]()
listt = [cognome!,sede!,progetto!]
//uisng Structs
struct progettostruct {
static var progetto : String?
}
struct datainizioserviziostruct {
static var datainizioservizio : String?
}
progettostruct.progetto = "4"
datainizioserviziostruct.datainizioservizio = "5"
listt.append(progettostruct.progetto!)
listt.append(datainizioserviziostruct.datainizioservizio!)
2) here you can have a look at console output along with my written code

Related

Putting a dictionary returned from func into a table view

I have a func which that is putting two lists together into a dictionary. I want this dictionary to print each [String : String] into a new cell on my table view. I'm only getting one cell back, which I know why (returning one item). However I can not figure out how to access my dictionary list to return each item in the dictionary.
Here is a picture of what I'm currently getting.
Screenshot of current results
Here is my struct and funcs to get the items and put into a dictionary.
//struct for the dictionary that holds all meals
struct RootData: Codable {
var meals: [MealDetails]
}
//struct for dessert details of each meal
struct MealDetails: Codable {
var id: String
var name: String
var instructions: String?
var image: String?
var strIngredient1: String?
var strIngredient2: String?
var strIngredient3: String?
var strIngredient4: String?
var strIngredient5: String?
var strIngredient6: String?
var strIngredient7: String?
var strIngredient8: String?
var strIngredient9: String?
var strIngredient10: String?
var strIngredient11: String?
var strIngredient12: String?
var strIngredient13: String?
var strIngredient14: String?
var strIngredient15: String?
var strIngredient16: String?
var strIngredient17: String?
var strIngredient18: String?
var strIngredient19: String?
var strIngredient20: String?
var strMeasure1: String?
var strMeasure2: String?
var strMeasure3: String?
var strMeasure4: String?
var strMeasure5: String?
var strMeasure6: String?
var strMeasure7: String?
var strMeasure8: String?
var strMeasure9: String?
var strMeasure10: String?
var strMeasure11: String?
var strMeasure12: String?
var strMeasure13: String?
var strMeasure14: String?
var strMeasure15: String?
var strMeasure16: String?
var strMeasure17: String?
var strMeasure18: String?
var strMeasure19: String?
var strMeasure20: String?
enum CodingKeys: String, CodingKey {
case id = "idMeal"
case name = "strMeal"
case instructions = "strInstructions"
case image = "strMealThumb"
case strIngredient1, strIngredient2, strIngredient3, strIngredient4, strIngredient5, strIngredient6,
strIngredient7, strIngredient8, strIngredient9, strIngredient10, strIngredient11, strIngredient12,
strIngredient13, strIngredient14, strIngredient15, strIngredient16, strIngredient17, strIngredient18,
strIngredient19, strIngredient20
case strMeasure1, strMeasure2, strMeasure3, strMeasure4, strMeasure5, strMeasure6, strMeasure7, strMeasure8, strMeasure9, strMeasure10, strMeasure11, strMeasure12, strMeasure13, strMeasure14, strMeasure15, strMeasure16, strMeasure17, strMeasure18, strMeasure19, strMeasure20
}
func getAllIngredients() -> [String] {
var ingredients = [String]()
ingredients.append(strIngredient1 ?? "")
ingredients.append(strIngredient2 ?? "")
ingredients.append(strIngredient3 ?? "")
ingredients.append(strIngredient4 ?? "")
ingredients.append(strIngredient5 ?? "")
ingredients.append(strIngredient6 ?? "")
ingredients.append(strIngredient7 ?? "")
ingredients.append(strIngredient8 ?? "")
ingredients.append(strIngredient9 ?? "")
ingredients.append(strIngredient10 ?? "")
ingredients.append(strIngredient11 ?? "")
ingredients.append(strIngredient12 ?? "")
ingredients.append(strIngredient13 ?? "")
ingredients.append(strIngredient14 ?? "")
ingredients.append(strIngredient15 ?? "")
ingredients.append(strIngredient16 ?? "")
ingredients.append(strIngredient17 ?? "")
ingredients.append(strIngredient18 ?? "")
ingredients.append(strIngredient19 ?? "")
ingredients.append(strIngredient20 ?? "")
return ingredients.filter{!$0.isEmpty}
}
func getAllMeasures() -> [String] {
var measures = [String]()
measures.append(strMeasure1 ?? "")
measures.append(strMeasure2 ?? "")
measures.append(strMeasure3 ?? "")
measures.append(strMeasure4 ?? "")
measures.append(strMeasure5 ?? "")
measures.append(strMeasure6 ?? "")
measures.append(strMeasure7 ?? "")
measures.append(strMeasure8 ?? "")
measures.append(strMeasure9 ?? "")
measures.append(strMeasure10 ?? "")
measures.append(strMeasure11 ?? "")
measures.append(strMeasure12 ?? "")
measures.append(strMeasure13 ?? "")
measures.append(strMeasure14 ?? "")
measures.append(strMeasure15 ?? "")
measures.append(strMeasure16 ?? "")
measures.append(strMeasure17 ?? "")
measures.append(strMeasure18 ?? "")
measures.append(strMeasure19 ?? "")
measures.append(strMeasure20 ?? "")
return measures
}
func getIngredientsAndMeasures() -> [String : String] {
var dictionary: [String : String] = [:]
let measures = getAllMeasures()
for (index, element) in getAllIngredients().enumerated() {
if !element.isEmpty {
dictionary[element] = measures[index]
}
}
return dictionary
}
}
Here is my view controller:
class DetailTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var idMeal: String = ""
var mealDetails = [MealDetails]()
//UI Oulets (Image, Dessert Name, Instructions, Ingredents)
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var instructionsText: UITextView!
#IBOutlet weak var detailTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
getApiDetailData {
print("data loaded")
self.view.reloadInputViews()
self.detailTableView.reloadData()
self.nameLabel.text = self.mealDetails[0].name
self.instructionsText.text = self.mealDetails[0].instructions
let urlString = (self.mealDetails[0].image)
let url = URL(string: urlString!)
self.imageView.downloaded(from: url!)
}
detailTableView.delegate = self
detailTableView.dataSource = self
}
func tableView(_ detailTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mealDetails.count
}
func tableView(_ detailTableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = "\(mealDetails[indexPath.row].getIngredientsAndMeasures())"
return cell
}
I've tried a number of things in the numbersOfRowsInSection function to access my dictionary. Any help would be much appreciated. I feel very close but not sure what I'm overlooking.
I think you should use a custom type for each ingredient and measurement
struct Ingredient {
let name: String
let measurement: String
}
and then you add a function to create an array of them from a MealDetails object by adding this method to the struct
func createIngredients() -> [Ingredient] {
return zip(getAllMeasures(), getAllIngredients()).map {
if $0.0.isEmpty { return nil }
return Ingredient(name: $0.0, measurement: $0.1)
}
}
Then you can have a property for this array in your view controller
var ingredients = [Ingredient]()
and assign to it in the closure in viewDidLoad
self.ingredients = self.mealDetails[0].createIngredients()
and then use it as the data source for your table view
func tableView(_ detailTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ingredients.count
}
func tableView(_ detailTableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = "\(ingredients[indexPath.row].name)" // or whatever you want here
return cell
}

How to create a model class and access the values from JSON response using Codable in ios swift?

I'm learning how to create a model class and using Codable protocol how to access the values for JSON response. Using Alamofire get a request for API call. Here my code
my model class
class UserDic:Codable{
var batters:Batter?
var id:Int?
var name:String?
var topping:[Topping]?
var ppu:Int?
var type:String?
}
class Topping:Codable{
var type:String?
var id:Int?
}
class Batter:Codable{
var id:Int?
var type:String?
}
class ViewController: UIViewController {
#IBOutlet weak var userTbl: UITableView!
var url:String!
var toppingVal:[Topping] = []
override func viewDidLoad() {
super.viewDidLoad()
url = "http://www.json-generator.com/api/json/get/bUNhsLXzVK?indent=2"
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
print("response--->",response)
guard response.data != nil else { return }
do{
let jsonResponse = try JSONDecoder().decode(UserDic.self, from: Data(response.data!))
self.toppingVal = jsonResponse.topping!
self.userTbl.reloadData()
}
print("reslut pass the :\(String(describing: jsonResponse.type))")
}catch{
print("Failed pass the :\(error)")
}
}
}
extension ViewController: UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toppingVal.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = userTbl.dequeueReusableCell(withIdentifier: "UserCell")
let aUser = toppingVal[indexPath.row]
cell?.textLabel?.text = String(aUser.id!)
return cell ?? UITableViewCell()
}
}
my question: Kindly view my json response and check my model class.How can i access the batters values and list in the UUtableview. Thanks advance.
You need
// MARK: - Empty
struct UserDic: Codable {
let topping: [Topping]
let name: String
let batters: Batters
let ppu: Double
let type: String
let id: Int
}
// MARK: - Batters
struct Batters: Codable {
let batter: [Topping]
}
// MARK: - Topping
struct Topping: Codable {
let type: String
let id: Int
}
let jsonResponse = try JSONDecoder().decode(UserDic.self, from: Data(response.data!))
self.toppingVal = jsonResponse.batters.batter
self.userTbl.reloadData()

How to save position of reordered cells in Collection View after I restart the app? Swift

When I am trying to reorder position of cells in UICollectionView using these two methods:
var teams: [Team]?
override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if let temp = teams?[sourceIndexPath.item] {
teams?[sourceIndexPath.item] = (teams?[destinationIndexPath.item])!
teams?[destinationIndexPath.item] = temp
}
print("Starting Index: \(sourceIndexPath.item)")
print("Ending Index: \(destinationIndexPath.item)")
}
It works fine however after restarting my app I want to save position of reordered cells.
Which approach could you recommend me?
Additional info:
The Array of "teams" is storing objects of class Team:
class Team: NSObject {
var id: String?
var name: String?
var logo: String?
var players: [Player]?
}
class Player: NSObject {
var alias: String?
var name: String?
var age: String?
var country: String?
var imageName: String?
var info: Info?
}
class Info: NSObject {
var screenshots: [String]?
var bio: String?
var gear: Gear?
var povs: [String]?
var cfg: Config?
}
class Gear: NSObject {
var monitor: String?
var mouse: String?
var mousepad: String?
var keyboard: String?
var headset: String?
}
class Config: NSObject {
var mouseSettings: [String]?
var monitorSettings: [String]?
var crosshaircfg: [String]?
}
Thank you in advance for your help!
I'd use UserDefaults for this.
I stored the position as an integer in the userDefaults and used the item name as the key.
How to store the positions
func saveReorderedArray() {
for (index, item) in yourArray.enumerated() {
let position = index + 1
UserDefaults.standard.set(position, forKey: item.name)
}
}
And upon application launch I called reorderArray function to grab the positions and stored it in a array of dictionaries using the item names as the keys.
How to retreive the positions
func reorderArray() {
var items: [[String: Int]] = []
// Get the positions
for item in yourArray {
var position = UserDefaults.standard.integer(forKey: item.name)
// If a new item is added, set position to 999
if position == 0 {
position = 999
}
items.append([itemName : position])
}
for item in items {
// Get position from dictionary
let position = Array(item.values)[0]
let itemName = Array(item.keys)[0]
// Get index from yourArray
let index = yourArray.index { (item) -> Bool in
item.name == itemName
}
// Arrange the correct positions for the cells
if let i = index {
let m = yourArray.remove(at: i)
// Append to last position of the array
if position == 999 {
yourArray.append(m)
}
else {
yourArray.insert(m, at: position - 1) // Insert at the specific position
}
}
}
}
I hope it helped!

UITableView with MVVM using Swift

I'm working on MVVM architecture in Swift with UITableView. For this, I have created sample table view.
Can any one please suggest whether I am going correct or any other improvements need to do?
The following are the classes for this architecture.
ViewController - Contains UITableView and its delegate and datasource methods.
class ViewController: UIViewController {
let PRODUCT_CELL_IDENTIFIER = "ProductCellIdentifier"
#IBOutlet weak var productTableView: UITableView!
var productViewModel: ProductViewModel = ProductViewModel()
}
//UITableView Delegate Methods
extension ViewController {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productViewModel.numberOfRowsInSection()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PRODUCT_CELL_IDENTIFIER) as! ProductTableViewCell
let product = productViewModel.productsArray[indexPath.row]
cell.productName.text = product.name
cell.productQuantity.text = "\(product.quantity)"
return cell
}
}
ProductViewModel: - This is ViewModel class.
class ProductViewModel: NSObject {
var productsArray = Array<Product>()
override init() {
let product1 = Product(name: "Prodcut1", image_url: "", quantity: 2)
let product2 = Product(name: "Prodcut2", image_url: "", quantity: 3)
productsArray.append(product1)
productsArray.append(product2)
}
func numberOfRowsInSection() -> Int {
return productsArray.count
}
}
Product - This is the model class
class Product: NSObject {
var name: String
var image_url: String
var quantity: Int
init(name: String, image_url: String, quantity: Int) {
self.name = name
self.image_url = image_url
self.quantity = quantity
}
}
ProductTableViewCell - This is UITableViewCell class
class ProductTableViewCell: UITableViewCell {
#IBOutlet weak var productQuantity: UILabel!
#IBOutlet weak var productName: UILabel!
#IBOutlet weak var productImageView: UIImageView!
}
You are doing good job, but you can even improve you product model with adding following function to get array of direct models. It is very useful when you have create array from web Api response.
class Product : NSObject
{
var imgUrl : String!
var name : String!
var quantity : Int!
init(dictionary: [String:Any])
{
imgUrl = dictionary["img_url"] as? String
name = dictionary["name"] as? String
quantity = dictionary["quantity"] as? Int
}
init(name: String, image_url: String, quantity: Int)
{
self.name = name
self.imgUrl = image_url
self.quantity = quantity
}
public class func modelsFromArray(array:[[String:Any]]) -> [Product]
{
var models:[Product] = []
for item in array
{
models.append(Product.init(dictionary:item))
}
return models
}
}
With Usage Like
let product1 = Product(name: "Prodcut1", image_url: "", quantity: 2) //Normal Case
let productList:[[String:Any]] =
[
["name":"Jaydeep","img_url":"xyz","quantity":1],
["name":"Jaydeep","img_url":"xyz","quantity":2],
["name":"Jaydeep","img_url":"xyz","quantity":3],
["name":"Jaydeep","img_url":"xyz","quantity":4],
["name":"Jaydeep","img_url":"xyz","quantity":5],
["name":"Jaydeep","img_url":"xyz","quantity":6]
]
//Assign Direct Dictionary to Get Array Of Models
/* Very useful when productList is dictionary from server response*/
let productArray:[Product] = Product.modelsFromArray(array: productList)
And Also your Cell Class is Improved By
class ProductTableViewCell: UITableViewCell {
#IBOutlet weak var productQuantity: UILabel!
#IBOutlet weak var productName: UILabel!
#IBOutlet weak var productImageView: UIImageView!
func setProductData(product:Product)
{
self.productName.text = product.name
self.productQuantity.text = "\(product.quantity)"
}
}
Usage:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PRODUCT_CELL_IDENTIFIER) as! ProductTableViewCell
let product = productViewModel.productsArray[indexPath.row]
cell.setProductData(product:product)
return cell
}
MVVM in iOS can be easily implemented without using third party dependencies. For data binding, we can use a simple combination of Closure and didSet to avoid third-party dependencies.
public final class Observable<Value> {
private var closure: ((Value) -> ())?
public var value: Value {
didSet { closure?(value) }
}
public init(_ value: Value) {
self.value = value
}
public func observe(_ closure: #escaping (Value) -> Void) {
self.closure = closure
closure(value)
}
}
An example of data binding from ViewController:
final class ExampleViewController: UIViewController {
private func bind(to viewModel: ViewModel) {
viewModel.items.observe(on: self) { [weak self] items in
self?.tableViewController?.items = items
// self?.tableViewController?.items = viewModel.items.value // This would be Momory leak. You can access viewModel only with self?.viewModel
}
// Or in one line:
viewModel.items.observe(on: self) { [weak self] in self?.tableViewController?.items = $0 }
}
override func viewDidLoad() {
super.viewDidLoad()
bind(to: viewModel)
viewModel.viewDidLoad()
}
}
protocol ViewModelInput {
func viewDidLoad()
}
protocol ViewModelOutput {
var items: Observable<[ItemViewModel]> { get }
}
protocol ViewModel: ViewModelInput, ViewModelOutput {}
final class DefaultViewModel: ViewModel {
let items: Observable<[ItemViewModel]> = Observable([])
// Implmentation details...
}
Later it can be replaced with SwiftUI and Combine (when a minimum iOS version of your app is 13)
In this article, there is a more detailed description of MVVM
https://tech.olx.com/clean-architecture-and-mvvm-on-ios-c9d167d9f5b3

Firebase Data is not loaded into tableview data model

The problem in the given code is, that the Firebase Data is not loaded into the Arrays before they get returned. Since I am new to swift I am really satisfied with my data model set up to load multiple sections into the tableview and don't want to change everything. The only problem is as I said, that the Firebase data collectors need some kind of a completion handler, but I don't really know how to apply them and I have no idea how to change the following code as well...
This is the class which defines an object:
class Court {
var AnzahlToreKoerbe: String?
var Breitengrad: String?
var Groesse: String?
var Hochgeladen: String?
var Laengengrad: String?
var Stadt: String?
var Stadtteil: String?
var Strasse: String?
var Untergrund: String?
var Upload_Zeitpunkt: Int?
var Platzart: String?
init(AnzahlToreKoerbeString: String, BreitengradString: String, GroesseString: String, HochgeladenString: String, LaengengradString: String, StadtString: String, StadtteilString: String, StrasseString: String, UntergrundString: String, UploadTime: Int, PlatzartString: String) {
AnzahlToreKoerbe = AnzahlToreKoerbeString
Breitengrad = BreitengradString
Groesse = GroesseString
Hochgeladen = HochgeladenString
Laengengrad = LaengengradString
Stadt = StadtString
Stadtteil = StadtteilString
Strasse = StrasseString
Untergrund = UntergrundString
Upload_Zeitpunkt = UploadTime
Platzart = PlatzartString
}
}
This is the class which collects the objects and load them into multiple arrays, which are then called with the getCOurts function in the tableViewController:
class Platzart
{
var Courts: [Court]
var name: String
init(name: String, Courttypes: [Court]) {
Courts = Courttypes
self.name = name
}
class func getCourts() -> [Platzart]
{
return [self.AllSoccer(), self.AllBasketball(), self.Test(), self.Test2()]
}
This is an example private class function which loads the data:
private class func AllSoccer() -> Platzart {
var allSoccer = [Court]()
let databaseref = FIRDatabase.database().reference()
databaseref.child("Court").child("Fußball").observe(.childAdded, with: { (snapshot) in
if let Courtdictionary = snapshot.value as? [String : Any] {
let city = Courtdictionary["Stadt"] as? String
let district = Courtdictionary["Stadtteil"] as? String
let street = Courtdictionary["Strasse"] as? String
let surface = Courtdictionary["Untergrund"] as? String
let latitude = Courtdictionary["Breitengrad"] as? String
let longitude = Courtdictionary["Laengengrad"] as? String
let size = Courtdictionary["Groesse"] as? String
let Userupload = Courtdictionary["Hochgeladen"] as? String
let timestamp = Courtdictionary["Upload_Zeitpunkt"] as? Int
let numberofHoops = Courtdictionary["AnzahlToreKoerbe"] as? String
let courttype = Courtdictionary["Platzart"] as? String
allSoccer.append(Court(AnzahlToreKoerbeString: numberofHoops!, BreitengradString: latitude!, GroesseString: size!, HochgeladenString: Userupload!, LaengengradString: longitude!, StadtString: city!, StadtteilString: district!, StrasseString: street!, UntergrundString: surface!, UploadTime: timestamp!, PlatzartString: courttype!))
print(allSoccer)
}
})
return Platzart(name: "Fußballplatz", Courttypes: allSoccer)
}
The data is then loaded into the tableview:
class CourtlistViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
lazy var Courtarrays: [Platzart] = {
return Platzart.getCourts()
}()
#IBOutlet weak var CourtlisttableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
CourtlisttableView.delegate = self
CourtlisttableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
CourtlisttableView.reloadData()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let Courttype = Courtarrays[section]
return Courttype.name
}
func numberOfSections(in tableView: UITableView) -> Int {
return Courtarrays.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Courtarrays[section].Courts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = CourtlisttableView.dequeueReusableCell(withIdentifier: "Court Cell", for: indexPath) as! CourtCell
let Platzarray = Courtarrays[indexPath.section]
let Sportplatz = Platzarray.Courts[indexPath.row]
cell.updateUI(Sportplatz)
return cell
}
}
This procedure works well with data which I append to an array manually. For the Firebase Sections (AllSoccer() and AllBasketball()) only the headers are loaded and displayed.

Resources