I am having issues displaying the make and model of the selected cell in another view controller connected by a segue. The Cells display the Vin Number and I want the make and model info for that specific vin number passed to another ViewController. I have attempted to set up passing the values but can not get it to work. Can someone take a look and see if they can spot where I went wrong?
Here is what my firebase database looks like:
Vehicles: {
5UXKR0C34H0X82785: {
VehicleInfo: {
make:"toyota",
model:"corolla",
VinNumber: "5UXKR0C34H0X82785"
}
}
}
Here is my Vehicle model class
import Foundation
import FirebaseDatabase
struct VehicleModel {
var Make: String?
var Model: String?
var VinNumber: String?
init(Make: String?, Model: String?, VinNumber: String?){
self.Make = Make
self.Model = Model
self.VinNumber = VinNumber
}
init(snapshot: DataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]
VinNumber = snapshotValue["VinNumber"] as? String
Make = snapshotValue["Make"] as? String
Model = snapshotValue["Model"] as? String
}
}
Here is my view controller code
import UIKit
import Firebase
import FirebaseDatabase
class InventoryTableViewController: UITableViewController{
var ref: DatabaseReference!
var refHandle: UInt!
var userList = [VehicleModel]()
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
tableView.delegate = self
tableView.dataSource = self
tableView?.register(UITableViewCell.self, forCellReuseIdentifier:
"cellId")
fetchUsers()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return userList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
// Set cell contents
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for:
indexPath) as UITableViewCell
let eachvehicle = userList[indexPath.row]
cell.textLabel!.text = "\(String(describing: eachvehicle.VinNumber))"
return cell
}
func fetchUsers(){
refHandle = ref.child("Vehicles").observe(.childAdded, with: {
(snapshot) in
if let dictionary = snapshot.childSnapshot(forPath:
"VehicleInfo").value as? [String: AnyObject] {
print(dictionary)
let VinNumber = dictionary["VinNumber"]
let Make = dictionary["Make"]
let Model = dictionary["Model"]
self.userList.insert(VehicleModel(Make: Make as? String, Model:
Model as? String, VinNumber: VinNumber as? String), at: 0)
self.tableView.reloadData()
}
})
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destination = storyboard.instantiateViewController(withIdentifier:
"AdditionalInfoViewController") as! AdditionalInfoViewController
navigationController?.pushViewController(destination, animated: true)
performSegue(withIdentifier: "toAdditionalInfo", sender: self)
let row = indexPath.row
print("working so far ")
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
makeToPass = currentCell.Model
modelToPass = currentCell.Make
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMapView" {
var viewController = segue.destination as!
AdditionalInfoViewController
viewController.makeToPass = makeToPass
viewController.modelToPass = modelToPass
}
}
structure for variables in my AdditionalInfoView Controller
var passedValue: String?
var latitudePassedValue: String?
var longitudePassedValue: String?
The problem seems to be in the parsing of the data from the database. The structure has make and model all lower case:
// ...
make:"toyota",
model:"corolla",
// ...
But in the parsing method you're addressing it with the first letter in uppercase:
// ...
Make = snapshotValue["Make"] as? String // "Make"
Model = snapshotValue["Model"] as? String // "Model"
// ...
Related
I am using a tableview to show a Project's title including the image.
I'm using FirebaseStorage and FirebaseDatabase.
The Problem is, that when I have only one protect, I get "Fatal error: Index out of range", as soon as I click on the Title.
When I have more than one Project you can see what happens in the video.
Maybe someone can help me, since something isn't right with the index handling. :)
import UIKit
import Kingfisher
import Foundation
import FirebaseStorage
import FirebaseDatabase
class HomeViewController: UIViewController {
// MARK: - Properties
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var addProject: UIButton!
var posts = [Post]()
var textToBeSent: String = ""
override func viewDidLoad() {
super.viewDidLoad()
UserService.posts(for: User.current) { (posts) in
self.posts = posts
self.tableView.reloadData()
}
Utilities.addShadowtoButton(addProject)
}
func configureTableView() {
// remove separators for empty cells
tableView.tableFooterView = UIView()
// remove separators from cells
tableView.separatorStyle = .none
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetails" {
let destVC = segue.destination as! ShowProjectDetailsViewController
destVC.post = sender as? Post
}
}
}
extension Collection where Indices.Iterator.Element == Index {
public subscript(safe index: Index) -> Iterator.Element? {
return (startIndex <= index && index < endIndex) ? self[index] : nil
}
}
// MARK: - UITableViewDataSource
extension HomeViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let post = posts[indexPath.row]
performSegue(withIdentifier: "toDetails", sender: post)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func numberOfSections(in tableView: UITableView) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.section]
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "PostImageCell") as! PostImageCell
let imageURL = URL(string: post.imageURL)
cell.postImageView.kf.setImage(with: imageURL)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "PostSubCell") as! PostSubCell
cell.projectName.text = post.projectTitle
return cell
default:
fatalError("Error: unexpected indexPath.")
}
}
}
// MARK: - UITableViewDelegate
extension HomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0:
let post = posts[indexPath.section]
return post.imageHeight
case 1:
return PostSubCell.height
default:
fatalError()
}
}
}
import Foundation
import FirebaseAuth.FIRUser
import FirebaseDatabase
import FirebaseUI
import FirebaseAuth
struct UserService {
static func posts(for user: User, completion: #escaping ([Post]) -> Void) {
let ref = Database.database().reference().child("posts").child(user.uid)
ref.observe(DataEventType.value, with: { (snapshot) in
guard let snapshot = snapshot.children.allObjects as? [DataSnapshot] else {
return completion([])
}
let posts = snapshot.reversed().compactMap(Post.init)
completion(posts)
})
}
}
import Foundation
import UIKit
import FirebaseDatabase.FIRDataSnapshot
class Post {
// Next let's add properties to store all the additional information we need. Add the following to your post class.
var key: String?
let imageURL: String
let imageHeight: CGFloat
let creationDate: Date
let imageName: String
let projectTitle: String
let projectLocation: String
let projectDescription: String
let projectBeginn: String
let projectEnd: String
// You'll get some compiler errors for not having any initializers or default values for certain properties. Let's go ahead and fix that:
init(imageURL: String, imageName: String, imageHeight: CGFloat, projectTitle: String, projectLocation: String, projectDescription: String, projectBeginn: String, projectEnd: String) {
self.imageURL = imageURL
self.imageName = imageName
self.imageHeight = imageHeight
self.creationDate = Date()
self.projectTitle = projectTitle
self.projectLocation = projectLocation
self.projectDescription = projectDescription
self.projectBeginn = projectBeginn
self.projectEnd = projectEnd
}
var dictValue: [String : Any] {
let createdAgo = creationDate.timeIntervalSince1970
return ["image_url" : imageURL,
"image_name" : imageName,
"image_height" : imageHeight,
"created_at" : createdAgo,
"projectTitle" : projectTitle,
"projectLocation" : projectLocation,
"projectDescription" : projectDescription,
"projectBeginn" : projectBeginn,
"projectEnd": projectEnd ]
}
init?(snapshot: DataSnapshot) {
guard let dict = snapshot.value as? [String : Any],
let imageURL = dict["image_url"] as? String,
let imageName = dict["image_name"] as? String,
let imageHeight = dict["image_height"] as? CGFloat,
let createdAgo = dict["created_at"] as? TimeInterval,
let projectTitle = dict["projectTitle"] as? String,
let projectLocation = dict["projectLocation"] as? String,
let projectDescription = dict["projectDescription"] as? String,
let projectBeginn = dict["projectBeginn"] as? String,
let projectEnd = dict["projectEnd"] as? String
else { return nil }
self.key = snapshot.key
self.imageURL = imageURL
self.imageName = imageName
self.imageHeight = imageHeight
self.creationDate = Date(timeIntervalSince1970: createdAgo)
self.projectTitle = projectTitle
self.projectLocation = projectLocation
self.projectDescription = projectDescription
self.projectBeginn = projectBeginn
self.projectEnd = projectEnd
}
}
Thanks for your help!
You created your numberOfSection by [Post]. And also you assigning performSegue on click of indexPath.row. So it's throws an error, you've to use indexPath.section instead of indexPath.row in didSelectItem() method
e.g.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let post = posts[indexPath.section] // Use here section instead of row
performSegue(withIdentifier: "toDetails", sender: post)
}
I am having issues getting my data from firebase to show on my TableView. I only want the vin number to display on the table view. Right now i am either getting cells that display "nil", or nothing in the cells.
My goal is to have each cell display the Vin Number.
Can someone take a look and let me know where i have an issue?
Thanks!!!
Alex
here is what my firebase database looks like
child --Vehicles
child--5UXKR0C34H0X82785
child-- VehicleInfo
then under the "vehicle Info" child it displays these three fields
make:"toyota"
model:"corolla"
VinNumber: "5UXKR0C34H0X82785"
Here is my Vehicle model class
import Foundation
import FirebaseDatabase
struct VehicleModel {
var Make: String?
var Model: String?
var VinNumber: String?
init(Make: String?, Model: String?, VinNumber: String?){
self.Make = Make
self.Model = Model
self.VinNumber = VinNumber
}
init(snapshot: DataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]
VinNumber = snapshotValue["VinNumber"] as? String
Make = snapshotValue["Make"] as? String
Model = snapshotValue["Model"] as? String
}
}
Here is my view controller code
import UIKit
import Firebase
import FirebaseDatabase
class InventoryTableViewController: UITableViewController{
var ref: DatabaseReference!
var refHandle: UInt!
var userList = [VehicleModel]()
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
tableView.delegate = self
tableView.dataSource = self
tableView?.register(UITableViewCell.self, forCellReuseIdentifier:
"cellId")
fetchUsers()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return userList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
// Set cell contents
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for:
indexPath) as UITableViewCell
let eachvehicle = userList[indexPath.row]
cell.textLabel!.text = "\(String(describing: eachvehicle.VinNumber))"
return cell
}
func fetchUsers(){
refHandle = ref.child("Vehicles").observe(.childAdded, with: {
(snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
print(dictionary)
let VinNumber = dictionary["VinNumber"]
let Make = dictionary["Make"]
let Model = dictionary["Model"]
self.userList.insert(VehicleModel(Make: Make as? String, Model:
Model as? String, VinNumber: VinNumber as? String), at: 0)
self.tableView.reloadData()
}
})
}
}
Also, I am having issues displaying the make and model of the selected cell in another view controller connected by a segue. I have attempted to set up passing the values but can not get it to work.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destination = storyboard.instantiateViewController(withIdentifier:
"AdditionalInfoViewController") as! AdditionalInfoViewController
navigationController?.pushViewController(destination, animated: true)
performSegue(withIdentifier: "toAdditionalInfo", sender: self)
let row = indexPath.row
print("working so far ")
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
makeToPass = currentCell.Model
modelToPass = currentCell.Make
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMapView" {
var viewController = segue.destination as! AdditionalInfoViewController
viewController.makeToPass = makeValueToPass
viewController.modelToPass = modelValueToPass
}
}
Correct me if I'm wrong, but this is your data structure, right?
Vehicles: {
5UXKR0C34H0X82785: {
VehicleInfo: {
make:"toyota",
model:"corolla",
VinNumber: "5UXKR0C34H0X82785"
}
}
}
Which means in order to access the data under VehicleInfo, you need to specify that location. There are a few ways you can do this, but one of them would be using childSnapshot(forPath:)
func fetchUsers(){
refHandle = ref.child("Vehicles").observe(.childAdded, with: {
(snapshot) in
if let dictionary = snapshot.childSnapshot(forPath: "VehicleInfo").value as? [String: AnyObject] {
print(dictionary)
let VinNumber = dictionary["VinNumber"]
let Make = dictionary["Make"]
let Model = dictionary["Model"]
self.userList.insert(VehicleModel(Make: Make as? String, Model:
Model as? String, VinNumber: VinNumber as? String), at: 0)
self.tableView.reloadData()
}
})
}
}
I am currently trying to receive an array of images with title from my Child's folder to the another offertableview which is connected by button from the detailViewController, but unfortunately I keep getting an error. Below I attached images of my firebase data structure and my mainstoryboard screenshot.
For the first table view I have a list of the restaurants and upon selecting a cell it transfers to the detail view controller which lists all the details of the restaurant (for that I've created a model of my restaurant) in that detailVC I have a button connected to the offerstableview which lists all the offers of that particular restaurant.
When I click to the button it transfers to the offers table view which results to the application shut down due to the error.
my offers tableview code:
var ref: DatabaseReference!
var offerImageArray = [String]()
var titleArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
fetchBars()
}
func fetchBars(){
ref.child("Paris").observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let imageSnap = snap.childSnapshot(forPath: "offers")
let dict = imageSnap.value as! [String: Any]
let imageUrl = dict["offer_image"] as? String
let titleUrl = dict["offer_title"] as? String
self.offerImageArray = [imageUrl! as String]
self.titleArray = [titleUrl! as String]
}
})
self.tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return offerImageArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OfferCell", for: indexPath) as! OffersTableViewCell
cell.offerImageView.sd_setImage(with: URL(string: self.offerImageArray[indexPath.row]))
cell.titleLabel.text = titleArray[indexPath.row]
return cell
}
Xcode error:
2017-08-16 10:26:33.652 Applic[1174]
[Firebase/Analytics][I-ACS003007] Successfully created Firebase
Analytics App Delegate Proxy automatically. To disable the proxy, set
the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2017-08-16 10:26:33.826 Applic[1174]
[Firebase/Analytics][I-ACS032003] iAd framework is not linked. Search
Ad Attribution Reporter is disabled. 2017-08-16 10:26:33.828
Applic[1174] [Firebase/Analytics][I-ACS023012] Firebase
Analytics enabled fatal error: unexpectedly found nil while unwrapping
an Optional value
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import SDWebImage
class OffersTableVC: UITableViewController {
var ref: DatabaseReference!
var offerImageArray = [String]()
var titleArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
fetchBars()
}
func fetchBars(){
Database.database().reference().child("paris").observeSingleEvent(of: .value, with: { (snapshot) in
print("Main Snapshot is \(snapshot)")
for child in snapshot.children {
let snap = child as! DataSnapshot
let imageSnap = snap.childSnapshot(forPath: "offers")
if let snapDict = imageSnap.value as? [String:AnyObject] {
let dictKeys = [String](snapDict.keys)
print(dictKeys)
let dictValues = [AnyObject](snapDict.values)
print(dictValues)
for each in dictValues{
let imageUrl = each["offer_image"] as? String
print(imageUrl!)
self.offerImageArray.append(imageUrl!)
}
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.reloadData()
}
// let dict = imageSnap.value as! [String: Any]
// let imageUrl = dict["offer_image"] as? String
// let titleUrl = dict["offer_title"] as? String
// self.offerImageArray = [imageUrl! as String]
// self.titleArray = [titleUrl! as String]
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return offerImageArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OfferCell", for: indexPath) as! OffersTableViewCell
cell.offerImageView.sd_setImage(with: URL(string: self.offerImageArray[indexPath.row]))
// cell.titleLabel.text = titleArray[indexPath.row]
return cell
}
}
1) in Appdelegate.swift add selectedBarname as follow
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var selectedBarName = String()
2) MainTableVc Add following code
After declaration of Class
let appDelegate = UIApplication.shared.delegate as! AppDelegate
in prepareForSegue
if segue.identifier == "DetailView", let bar = selectedBar{
appDelegate.selectedBarName = bar.barName
3) OfferTableVc
now just call this function and Done but do not call your fetchBars now just getOffers
func getOffers() {
let databaseRef = Database.database().reference().child("aktau")
databaseRef.queryOrdered(byChild: "bar_name").queryEqual(toValue: self.appDelegate.selectedBarName).observe(.value, with: { snapshot in
if ( snapshot.value is NSNull ) {
print("not found)")
} else {
print(snapshot.value!)
for child in snapshot.children {
let snap = child as! DataSnapshot
let imageSnap = snap.childSnapshot(forPath: "offers")
if let snapDict = imageSnap.value as? [String:AnyObject] {
let dictValues = [AnyObject](snapDict.values)
for each in dictValues{
let imageUrl = each["offer_image"] as? String
print(imageUrl!)
self.offerImageArray.append(imageUrl!)
}
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.reloadData()
}
}
}
})
}
How do I make my Table View look something more like this instead of just standard horizontal cells. I want it to look like the example images put below, what do I need to do? My code for my tableView is down below as well.
import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage
struct postStruct {
let title : String!
let author : String!
let date : String!
let article : String!
let downloadURL : String!
}
class NewsViewController: UITableViewController {
var posts = [postStruct]()
override func viewDidLoad() {
super.viewDidLoad()
let ref = Database.database().reference().child("Posts")
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount)
for rest in snapshot.children.allObjects as! [DataSnapshot] {
guard let value = rest.value as? Dictionary<String,Any> else { continue }
guard let title = value["Title"] as? String else { continue }
guard let downloadURL = value["Download URL"] as? String else { continue }
guard let author = value["Author"] as? String else { continue }
guard let date = value["Date"] as? String else { continue }
guard let article = value["Article"] as? String else { continue }
let post = postStruct(title: title, author: author, date: date, article: article, downloadURL: downloadURL)
self.posts.append(post)
}
self.posts = self.posts.reversed(); self.tableView.reloadData()
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let label1 = cell?.viewWithTag(1) as! UILabel
label1.text = posts[indexPath.row].title
let imageView = cell?.viewWithTag(2) as! UIImageView
let post = self.posts[indexPath.row];
imageView.sd_setImage(with: URL(string: post.downloadURL), placeholderImage: UIImage(named: "placeholder"))
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detail" {
if let indexPath = tableView.indexPathForSelectedRow {
let destVC = segue.destination as! DetailNewsViewController
destVC.titleText = posts[indexPath.row].title
destVC.dateText = posts[indexPath.row].date
destVC.authorText = posts[indexPath.row].author
destVC.bodyText = posts[indexPath.row].article
destVC.headerPhoto = posts[indexPath.row].downloadURL
}
}
}
}
Maybe you can use different Cells with different identifier in your storyboard. Design each cell as you want and in use cell rowAtIndexPath return the cell you want.
I think you should use UICollectionView instead of tableView. And create your custom layout. See this great tutorial to understand custom layouts.
https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest
I have LoginViewController where a user logs in. Upon doing this details are fetched of communities they are in.
These names of these communities are passed to ViewController with this section of code:
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
if let arr = json?["communities"] as? [[String:String]] {
self.communitiesArray = arr.flatMap { $0["name"]!}
}
self.performSegue(withIdentifier: "backHome", sender: self.communitiesArray)
and
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "backHome" {
let createViewController: ViewController = segue.destination as! ViewController
createViewController.communities = communitiesArray
}
A UITableView is then used to display the list of communities using this code in ViewController:
var communities = [String]()
#IBOutlet weak var communitiesTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.communitiesTableView.delegate = self
self.communitiesTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.communities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let title = self.communities[indexPath.row]
let cell = UITableViewCell()
cell.textLabel?.text = title
return cell
}
If a user selects a community, this opens a new view controller 'ShowCommunityViewController` and passes a variable containing its name:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedCellTitle = self.communities[indexPath.row]
self.performSegue(withIdentifier: "showCommunitySegue", sender: self)
}
However, I also want to pass the 'id' of this community which is also contained within "communities" alongside 'name'
I was hoping I could do something like this in my LoginViewController:
if let arr = json?["communities"] as? [[String:String]] {
self.communitiesArray = arr.flatMap { $0["name"]!
self.communitiesArray = arr.flatMap { $1["id"]!
}
}
self.performSegue(withIdentifier: "backHome", sender: self.communitiesArray)
And then somehow pass both the 'name' and 'id' together from 'ViewController' to my new destination ShowCommunityViewController. But that doesn't exist as Syntax and was just something I made up!
What is the best way to pass the name and id together?
You can zip the two together. i.e.
let names = arr.flatMap { $0["name"]! }
let ids = arr.flatMap { $1["id"]! }
let communities = zip(names, ids)
Create a model object, like the following:
class Community {
let id: String
let name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
}
Once you have your JSON, create an array of Community, instead of just using a String array.
var communities = [Community]()
if let arr = json?["communities"] as? [[String:String]] {
communities = arr.flatMap({ (candidate) -> Community? in
guard let id = candidate["id"], let name = candidate["name"] else { return nil }
return Community(id: id, name: name)
})
}
I am not exactly sure where do you have this data. But this should be passed to your vc, where you can select the community.
After this, instead of keeping track of the selectedCellTitle, keep track of selectedCommunity and assign that to your vc in prepareforsegue.