I Have three section in a UITableview ie - Categories, MyAccount and Support were MyAccount and Support Section are populated with static data but the categories section is to be populated with web api response by the help of Alamofire & SwiftyJSON I am getting the result which i want but can't figure out how to populate the particular section
Here is my code...
import UIKit
import Alamofire
import SwiftyJSON
class MenuView: UIViewController, KYDrawerControllerDelegate,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var menuTableview: UITableView!
struct Objects {
var sectionName : String!
var sectionObjects : [String]!
}
var objectsArray = [Objects]()
var categoriesArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let bar:UINavigationBar! = self.navigationController?.navigationBar
//self.title = "Home Screen"
bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
bar.shadowImage = UIImage()
bar.alpha = 0.0
objectsArray = [
Objects(sectionName: "", sectionObjects: ["Home"]),
Objects(sectionName: "Categories", sectionObjects: categoriesArr),
Objects(sectionName: "My Account", sectionObjects: ["My WishList", "My Profile", "My Addresses", "My Order", "Log out"]),
Objects(sectionName: "Support", sectionObjects: ["About Us", "Delivery Information", "Privacy Policy", "Terms & Conditions", "Contact Us", "Return Policy"])]
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
callAPI()
}
//MARK: UITabView DataSources
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
cell.textLabel?.text = objectsArray[indexPath.section].sectionObjects[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectsArray[section].sectionObjects.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return objectsArray.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return objectsArray[section].sectionName
}
func callAPI () {
//SwiftSpinner.show("Sending request..")
Alamofire.request(.POST, "http://www.picknget.com/webservice/index.php/Home/get_all_category")
.responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
if let _statusCode = json["status"].string {
print("the ststus code is ", _statusCode)
if (_statusCode == "1"){
self.parseJSON(json)
}
else {
self.callAlert("Alert", _msg: "Something Went Wrong Kindly Check Your Connection & Try Agian")
}
}
//print ("json result ", json)
}
}.responseString { response in
//print("response ",response.result.value)
}
}
func parseJSON(json: JSON) {
for result in json["category"].arrayValue {
print("The available categories are",result["MainCatName"].stringValue)
self.categoriesArr.append(result["MainCatName"].stringValue)
}
print("########")
objectsArray[2].sectionObjects = categoriesArr
print(categoriesArr.count)
print(categoriesArr[0],categoriesArr[1])
dispatch_async(dispatch_get_main_queue(),{
self.menuTableview.reloadData()
});
}
Any Suggestion ,
Thank you in advance
Here is the updated code which works.. Thank to #pbasdf Sir Support and guidance :)
import UIKit
import Alamofire
import SwiftyJSON
class MenuView: UIViewController, KYDrawerControllerDelegate,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var menuTableview: UITableView!
struct Objects {
var sectionName : String!
var sectionObjects : [String]!
}
var objectsArray = [Objects]()
var categoriesArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let bar:UINavigationBar! = self.navigationController?.navigationBar
//self.title = "Home Screen"
bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
bar.shadowImage = UIImage()
bar.alpha = 0.0
objectsArray = [
Objects(sectionName: "", sectionObjects: ["Home"]),
Objects(sectionName: "Categories", sectionObjects: categoriesArr),
Objects(sectionName: "My Account", sectionObjects: ["My WishList", "My Profile", "My Addresses", "My Order", "Log out"]),
Objects(sectionName: "Support", sectionObjects: ["About Us", "Delivery Information", "Privacy Policy", "Terms & Conditions", "Contact Us", "Return Policy"])]
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
callAPI()
}
//MARK: UITabView DataSources
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
cell.textLabel?.text = objectsArray[indexPath.section].sectionObjects[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectsArray[section].sectionObjects.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return objectsArray.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return objectsArray[section].sectionName
}
func callAPI () {
Alamofire.request(.POST, "http://www.picknget.com/webservice/index.php/Home/get_all_category")
.responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
if let _statusCode = json["status"].string {
print("the ststus code is ", _statusCode)
if (_statusCode == "1"){
self.parseJSON(json)
}
else {
self.callAlert("Alert", _msg: "Something Went Wrong Kindly Check Your Connection & Try Agian")
}
}
//print ("json result ", json)
}
}.responseString { response in
//print("response ",response.result.value)
}
}
func parseJSON(json: JSON) {
for result in json["category"].arrayValue {
print("The available categories are",result["MainCatName"].stringValue)
self.categoriesArr.append(result["MainCatName"].stringValue)
}
print("########")
objectsArray[2].sectionObjects = categoriesArr
print(categoriesArr.count)
print(categoriesArr[0],categoriesArr[1])
dispatch_async(dispatch_get_main_queue(),{
self.menuTableview.reloadData()
});
}
Related
I created four label inside the table view cell to fetch the data from Api . The link is https://coinmap.org/api/v1/venues/ . I have two swift file one is to define the tabelview property and other one is for Label with cell . When I run the app it displaying the tableview cell but not displaying the data with label . Here is the model .
// MARK: - Welcome
struct Coin: Codable {
let venues: [Venue]
}
// MARK: - Venue
struct Venue: Codable {
let id: Int
let lat, lon: Double
let category, name: String
let createdOn: Int
let geolocationDegrees: String
enum CodingKeys: String, CodingKey {
case id, lat, lon, category, name
case createdOn = "created_on"
case geolocationDegrees = "geolocation_degrees"
}
}
Here is the Network Manager .
class NetworkManager {
func getCoins(from url: String, completion: #escaping (Result<Coin, NetworkError>) -> Void ) {
guard let url = URL(string: url) else {
completion(.failure(.badURL))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(.other(error)))
return
}
if let data = data {
//decode
do {
let response = try JSONDecoder().decode(Coin.self, from: data)
completion(.success(response))
} catch let error {
completion(.failure(.other(error)))
}
}
}
.resume()
}
}
Here is the presenter .
class VenuePresenter : VanueProtocol{
// creating instance of the class
private let view : VanueViewProtocol
private let networkManager: NetworkManager
private var vanues = [Venue]()
var rows: Int{
return vanues.count
}
// initilanize the class
init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
self.view = view
self.networkManager = networkmanager
}
func getVanue(){
let url = "https://coinmap.org/api/v1/venues/"
networkManager.getCoins(from: url) { result in
switch result {
case.success(let respone):
self.vanues = respone.venues
DispatchQueue.main.async {
self.view.resfreshTableView()
}
case .failure(let error):
DispatchQueue.main.async {
self.view.displayError(error.errorDescription ?? "")
print(error)
}
}
}
}
func getId(by row: Int) -> Int {
return vanues[row].id
}
func getLat(by row: Int) -> Double {
return vanues[row].lat
}
func getCreated(by row: Int) -> Int {
return vanues[row].createdOn
}
func getLon(by row: Int) -> Double? {
return vanues[row].lon
}
}
Here is the view controller .
class ViewController: UIViewController{
private var presenter : VenuePresenter!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
presenter = VenuePresenter(view: self)
presenter.getVanue()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DisplayView1")
// Do any additional setup after loading the view.
}
private func setUpUI() {
tableView.dataSource = self
tableView.delegate = self
}
}
extension ViewController : VanueViewProtocol{
func resfreshTableView() {
tableView.reloadData()
}
func displayError(_ message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(doneButton)
present(alert, animated: true, completion: nil)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
presenter.rows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: DisplayView.identifier, for: indexPath) as? DisplayView
else { return UITableViewCell() }
let row = indexPath.row
let id = presenter.getId(by: row)
let lat = presenter.getLat(by: row)
guard let lon = presenter.getLon(by: row) else { return UITableViewCell() }
let createdOn = presenter.getCreated(by: row)
cell.configureCell(id: id, lat: lat, lon: lon, createdOn: createdOn)
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
Here is the display view swift .
class DisplayView: UITableViewCell{
static let identifier = "DisplayView1"
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
func configureCell(id: Int ,lat : Double , lon : Double , createdOn: Int){
label1.text = String(id)
label2.text = String(lat)
label3.text = String(lon)
label4.text = String(createdOn)
}
}
Here is the screenshot is empty not displaying the data .
You are registering a generic cell:
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DisplayView1")
You need to register your custom cell:
self.tableView.register(DisplayView.self, forCellReuseIdentifier: DisplayView.identifier)
I have already implement tableview and searchbar, and show skills vName on row and trade VName on section
my issue is,
I want to show only skills vName when search in searchbar in updateSearchResultsForSearchController method
i have tried that method but cannot success.
#JSON Response from API
{
"category": [
{
"iTraderCategoryId": "001",
"vName": "Build",
"vCategoryCode": "builder",
"skill": [
{
"iTraderSkillId": "1",
"iTraderCategoryId": "11",
"vName": "skillName1"
},
{
"iTraderSkillId": "2",
"iTraderCategoryId": "22",
"vName": "skillName2"
}
]
},
{
"iTraderCategoryId": "002",
"vName": "TV",
"vCategoryCode": "tv",
"skill": [
{
"iTraderSkillId": "3",
"iTraderCategoryId": "33",
"vName": "skillName3"
},
{
"iTraderSkillId": "4",
"iTraderCategoryId": "44",
"vName": "skillName4"
},
{
"iTraderSkillId": "5",
"iTraderCategoryId": "55",
"vName": "skillName5"
}
]
}
]
}
#my tableview controller code is,
import UIKit
import RealmSwift
import Alamofire
import RxSwift
//class SectionTableViewController: UITableViewController, UISearchResultsUpdating,UISearchBarDelegate, UISearchControllerDelegate {
class SectionTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
var selectedIngredients : Set<IndexPath> = []
var searchController : UISearchController!
var searchTradeSkills : UISearchController!
var selectedTrad: Trade?
var filteredObjects = [SkillDTO]()
var isSearching = false
var lastSelectedIndexPath : Int?
var totalSkills = [Int : Bool]()
// var filterData : [String]!
private let viewModel = TradeSelectionViewModel()
var selectedTradeHandler: ((_ trade: Trade) -> Void)?
private let bag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
searchBarSetup()
callAPI()
}
func searchBarSetup() {
tableView.allowsMultipleSelection = true
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableView.automaticDimension
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
}
func callAPI(){
UserApi().getTradieSkills().subscribe(onNext: { (result: Result<TradeSelectionViewModel>) in
switch result {
case .success(model: _):
print(result)
case .error(error: _):
print("error")
}
}).disposed(by: bag)
}
// i don't know how to implement and show only skills when search
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text!
print(viewModel.categorySkills)
if searchString.isEmpty {
filteredObjects.removeAll()
}else{
let filterObject = viewModel.categorySkills.map({
$0.skill
})
.reduce([], +).filter({
($0.vName?.lowercased().contains(searchString.lowercased()))!
})
filteredObjects = filterObject
// print("filter data is \(filteredObjects)")
// let filterObject = viewModel.categorySkills.map({
// $0.skill
// })
// .reduce([], +).filter({
// ($0.vName?.lowercased().contains(searchString.lowercased()))!
// })
// let filterObjects = viewModel.catSkills.compactMap({
// $0.vName?.filter({
// $0.lowercased().contains(searchString.lowercased())
// })
// })
// filteredObjects = filterObject
// print("filter data count is in search before \(filteredObjects.count)")
// print("filter data is \(filteredObjects)")
}
if searchController.isActive {
isSearching = true
}else{
isSearching = false
}
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.categorySkills.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching && searchController.searchBar.text != ""{
return filteredObjects.count
//return filteredObjects[section].skillName.count
// return filteredObjects[section].count //final
}else{
let section = viewModel.categorySkills[section]
return section.skill.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if isSearching && searchController.searchBar.text != "" {
let text =
filteredObjects[indexPath.row].vName
cell.textLabel?.text = text
}else{
cell.textLabel?.text = viewModel.categorySkills[indexPath.section].skill[indexPath.row].vName
}
if selectedIngredients.contains(indexPath){
cell.accessoryType = .checkmark
cell.backgroundColor = UIColor.lightGray
}else{
cell.accessoryType = .none
cell.backgroundColor = .none
}
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let titleText = viewModel.categorySkills[section].vName
return titleText
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
lastSelectedIndexPath = indexPath.section
if self.selectedIngredients.contains(indexPath){
self.selectedIngredients.remove(indexPath)
totalSkills[indexPath.row] = false
}else{
self.selectedIngredients.insert(indexPath)
totalSkills[indexPath.row] = true
}
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
print(selectedIngredients)
if lastSelectedIndexPath != nil {
if lastSelectedIndexPath != indexPath.section {
selectedIngredients.removeAll()
print(selectedIngredients)
}
}
return indexPath
}
}
Trade Structure
import Foundation
struct Trade {
let categoryId: String
let trade: String
let skill : [Skills]
}
struct Skills {
let skillId: String
let skillName: String
}
#ViewModelFile
import Foundation
import RealmSwift
class TradeSelectionViewModel {
init() {
load()
}
private(set) var trades: [Trade] = []
var categorySkills : Results<TradeCategorySkillDTO> = DataManager.shared.get()
private func load() {
trades.removeAll()
categorySkills = categorySkills.sorted(byKeyPath: "vName")
categorySkills.forEach({
trades.append(Trade(categoryId: $0.iTraderCategoryID, trade: $0.vName))
})
// print(trades)
}
}
RealmFile for Trade data
import Foundation
import Realm
import RealmSwift
#objcMembers class TradeCategorySkillDTO: Object, Codable {
dynamic var iTraderCategoryID: String = ""
dynamic var vName: String = ""
dynamic var skill = List<SkillDTO>()
enum CodingKeys: String, CodingKey {
case iTraderCategoryID = "iTraderCategoryId"
case vName
case skill
}
override static func primaryKey() -> String? {
return "iTraderCategoryID"
}
}
RealmFile for Skill Data
import Foundation
import Realm
import RealmSwift
#objcMembers class SkillDTO: Object, Codable {
dynamic var iTraderSkillID: String = ""
dynamic var iTraderCategoryID: String = ""
dynamic var vName: String?
enum CodingKeys: String, CodingKey {
case iTraderSkillID = "iTraderSkillId"
case iTraderCategoryID = "iTraderCategoryId"
case vName
}
override static func primaryKey() -> String? {
return "iTraderSkillID"
}
}
I get
Referencing instance method 'encode' on 'Array' requires that '(item: String?, price: String?, salesPrice: String?)' conform to 'Encodable' "
this error in the storeData() function. Did I even save the tuple correctly in user defaults? If anyone can help that would be great!Any help is appreciated!
import UIKit
let defaults = UserDefaults(suiteName: "com.Saving.Data")
struct Product: Codable {
var title: String
var price: String
var salePrice: String
}
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var items: [(item: String?, price: String?, salesPrice: String?)] = []
override func viewDidLoad() {
super.viewDidLoad()
getData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
getData()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(true)
storeData()
}
override var prefersStatusBarHidden: Bool {
return true
}
#IBAction func addButtonTapped(_ sender: Any) {
let alert = UIAlertController(title: "Product Information", message: nil, preferredStyle: .alert)
alert.addTextField { (itemTF) in
itemTF.placeholder = "Item"
}
alert.addTextField { (textField) in
textField.placeholder = "Price"
}
alert.addTextField { (textField) in
textField.placeholder = "Sale Price"
}
let action = UIAlertAction(title: "Add", style: .default) { (_) in
var product : (item: String, price: String, salesPrice: String) = ("","","")
if let textField1 = alert.textFields?[0], let text = textField1.text {
print(text)
product.item = text
}
if let textField2 = alert.textFields?[1], let text = textField2.text {
print(text)
product.price = text
}
if let textField3 = alert.textFields?[2], let text = textField3.text {
print(text)
product.salesPrice = text
}
self.add(product)
}
alert.addAction(action)
present(alert, animated: true)
storeData()
}
func add(_ product: (item: String, price: String, salesPrice: String)) {
let index = 0
items.insert(product, at: index)
let indexPath = IndexPath(row: index, section: 0)
tableView.insertRows(at: [indexPath], with: .left)
storeData()
}
func storeData() {
if let data = try? PropertyListEncoder().encode(items) {
UserDefaults.standard.set(data, forKey: "savedData")
}
}
func getData() {
if let data = UserDefaults.standard.data(forKey: "savedData") {
let items = try! PropertyListDecoder().decode([Product].self, from: data)
print(items)
}
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let product = items[indexPath.row]
cell.textLabel?.text = product.item
print(product.price ?? "")
print(product.salesPrice ?? "")
cell.contentView.backgroundColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)
cell.textLabel?.textColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)
tableView.separatorColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
items.remove(at: indexPath.row)
tableView.reloadData()
storeData()
}
}
As already mentioned in the comments it's incomprehensible why you use an extra tuple with the same design as your struct Product. This causes your problems.
So get rid of the tuple.
Declare items
var items = [Product]()
Replace the alert action with
let action = UIAlertAction(title: "Add", style: .default) { _ in
let item = alert.textFields?[0].text ?? ""
let price = alert.textFields?[1].text ?? ""
let salesPrice = alert.textFields?[2].text ?? ""
let product = Product(item: item, price: price, salesPrice: salesPrice)
self.addProduct(product)
}
Replace add with
func addProduct(_ product: Product) {
let index = 0
items.insert(product, at: index)
let indexPath = IndexPath(row: index, section: 0)
tableView.insertRows(at: [indexPath], with: .left)
storeData()
}
Replace getData with
func getData() {
if let data = UserDefaults.standard.data(forKey: "savedData") {
do {
items = try PropertyListDecoder().decode([Product].self, from: data)
print(items)
tableView.reloadData()
} catch { print(error) }
}
}
Side note: Be aware that the code saves the data in standard UserDefaults, not in your custom suite.
And finally – not related to the issue – to get a nice animation in tableView:commit editingStyle: replace
tableView.reloadData()
with
tableView.deleteRows(at: [indexPath], with: .fade)
I followed this Tutorial
And it works fine. Now if I try to take the sections data from a JSON this also works fine, but I have problems displaying everything.
This is what i did:
// TestVC.swift
// WinterdienstTest
//
// Created by zwipf on 09.02.17.
// Copyright © 2017 Squirrel. All rights reserved.
//
import UIKit
class TestVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let sections: [String] = ["Tour 1", "Tour 2", "Tour 3"]
var adressTour1: [String] = []
var adressTour2: [String] = []
var adressTour3: [String] = []
var adressTourALL: [Int: [String]] = [:]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// URL abrufen
let url = NSURL(string: "https://api.myjson.com/bins/mml65")
let request = NSMutableURLRequest(url: url! as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
// JSON parsen und Ergebins in eine Liste von assoziativen Arrays wandeln
let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
// Daten auslesen
if let Liegenschaften = responseString["Liegenschaften"] as? [AnyObject] {
for liegenschaft in Liegenschaften {
if let Winterdienst = liegenschaft["Winterdienst"] as? [AnyObject] {
for winterdienst in Winterdienst {
let tour = winterdienst["Tour"] as! String
if tour == "1" {
let adresse = liegenschaft["Adresse"] as! String
self.adressTour1.append(adresse)
}
if tour == "2" {
let adresse = liegenschaft["Adresse"] as! String
self.adressTour2.append(adresse)
}
if tour == "3" {
let adresse = liegenschaft["Adresse"] as! String
self.adressTour3.append(adresse)
}
}
}
}
}
self.adressTourALL = [0:self.adressTour1, 1:self.adressTour2, 2:self.adressTour3]
}
// UI-Darstellung aktualisieren
//OperationQueue.main.addOperation {
// self.tableView.reloadData()
//}
// task.resume()
print(self.adressTourALL)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return adressTourALL.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell");
}
print(adressTourALL[indexPath.section]![indexPath.row])
cell!.textLabel!.text = adressTourALL[indexPath.section]![indexPath.row]
return cell!
}
}
Hope somebody can help me!
Among the others, you need to put this inside your code:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section{
case 0:
return self.adressTour1.count
case 1:
return self.adressTour2.count
case 2:
return self.adressTour2.count
default:
return 1
}
I'm attempting to display a dictionary in the following format in a tableView (storyboard shown below):
var guestList = ["Event 1": ["Guest 1", "Guest 2", "Guest 3"], "Event 2": ["Guest 1", "Guest 2"], "Event 3": ["Guest 1", "Guest 2"], "Event 4": ["Guest 1", "Guest 2"]]
The data gets added to the objectArray variable successfully, but for some reason, none of the guests are showing in the table (see screenshot below):
import UIKit
import Parse
class RSVPTableViewController: UITableViewController {
var guestList = [String : [String]]()
let eventList = ["Hindu", "Reception", "Sangeet", "Tibetan"]
struct Objects {
var sectionName : String!
var sectionObjects : [String]!
}
var objectArray = [Objects]()
override func viewDidLoad() {
super.viewDidLoad()
for event in eventList { guestList[event] = [String]() }
let query = PFQuery(className:"GuestList")
query.whereKey("Family", equalTo: "Family1")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let family = objects {
print(family)
for guest in family {
for event in self.eventList {
if let invited = guest.valueForKey("\(event)Invite") as? Bool {
if invited {
self.guestList[event]!.append(guest.valueForKey("GuestName") as! String)
}
}
}
}
print(self.guestList)
for (key, value) in self.guestList {
print("\(key) -> \(value)")
self.objectArray.append(Objects(sectionName: key, sectionObjects: value))
self.tableView.reloadData()
}
print(self.objectArray)
}
} else {
print(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return objectArray.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return objectArray[section].sectionObjects.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return objectArray[section].sectionName
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row]
return cell
}
}
SOLUTION:
I added self.tableView.reloadData() in my viewDidLoad and it worked.