I am building an app which uses Firebase's database service. I am trying to load the data into a table view but I am unable to do so. I can't seem to figure out what's going wrong. The code is also not giving me any errors. I've checked the database permissions on Firebase and they seem to be good. Here's my code:
import UIKit
import Firebase
struct postStruct {
let word : String!
let wordType : String!
}
class sentenceBuilderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var wordSearchBar: UISearchBar!
#IBOutlet weak var wordsTableView: UITableView!
var posts = [postStruct]()
override func viewDidLoad() {
wordsTableView.reloadData()
getWordsFromDatabase()
super.viewDidLoad()
wordsTableView.delegate = self
wordsTableView.dataSource = self
}
func getWordsFromDatabase() {
let databaseRef = Database.database().reference()
databaseRef.child("wordList").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {
snapshot in
let word = (snapshot.value as? NSDictionary)!["word"] as? String
let wordType = (snapshot.value as? NSDictionary
)!["wordType"] as? String
self.posts.insert(postStruct(word: word, wordType: wordType), at: 0)
})
wordsTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = wordsTableView.dequeueReusableCell(withIdentifier: "Cell")
let wordLabel = cell?.viewWithTag(1) as! UILabel
wordLabel.text = posts[indexPath.row].word
let wordTypeLabel = cell?.viewWithTag(2) as! UILabel
wordTypeLabel.text = posts[indexPath.row].wordType
return cell!
}
}
Any help and inputs would be appreciated! Thanks!
The problem is that you are just observing a single event here:
databaseRef.child("wordList").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {
snapshot in
What this does is that it justs goes through your database and once it finds any child, it displays that one without going further. What you need to do is change it to observe like this:
func getAllWordsFromDatabase() {
let databaseRef = Database.database().reference()
databaseRef.child("wordList").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let word = (snapshot.value as? NSDictionary)!["word"] as? String
let wordType = (snapshot.value as? NSDictionary)!["wordType"] as? String
self.posts.append(postStruct(word: word, wordType: wordType))
DispatchQueue.main.async {
self.wordsTableView.reloadData()
}
})
}
Try implementing this and it should work.
Move the "getWordsFromDatabase()" line in "viewDidLoad" function to AFTER you assign the delegate and data source, like this:
override func viewDidLoad() {
super.viewDidLoad()
wordsTableView.delegate = self
wordsTableView.dataSource = self
getWordsFromDatabase()
}
Also you can try to add a "reloadData()" method in the databaseRef block on the main queue, like this:
let databaseRef = Database.database().reference()
databaseRef.child("wordList").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {
snapshot in
let word = (snapshot.value as? NSDictionary)!["word"] as? String
let wordType = (snapshot.value as? NSDictionary
)!["wordType"] as? String
self.posts.insert(postStruct(word: word, wordType: wordType), at: 0)
DispatchQueue.main.async {
wordsTableView.reloadData()
}
})
Related
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 was making an app for one of my family members so that they could better manage their clients but ran into some issues. This is my first time using Firebase and I just can't seem to get my code to work! The part in which I am getting stuck involves Firebase's Realtime Database, and I am working in XCode 8.3 with Swift 3.1.
Code:
import UIKit
import FirebaseCore
import FirebaseDatabase
import FirebaseAuth
var specClientId = ""
class MyCell: UITableViewCell {
#IBOutlet var nameCell: UILabel!
#IBOutlet var statusCell: UILabel!
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var ref: FIRDatabaseReference!
var tableArray: [String] = []
var clientId: [String] = []
var statusArray:[String] = []
#IBAction func signOut(_ sender: Any) {
UserDefaults.resetStandardUserDefaults()
performSegue(withIdentifier: "segueBackLogin", sender: self)
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableArray.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellFront") as! MyCell
cell.nameCell.text = tableArray[indexPath.row]
cell.statusCell.text = statusArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
specClientId = clientId[indexPath.row]
ref.child("Users").child(specClientId).child("lastUpdate").removeValue()
performSegue(withIdentifier: "segue", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
if FIRApp.defaultApp() == nil {
FIRApp.configure()
}
ref = FIRDatabase.database().reference()
ref.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let specificValues = value?.allKeys
self.tableArray.removeAll()
self.statusArray.removeAll()
self.clientId.removeAll()
var it = 0
for Uservalue in specificValues! {
self.tableArray.append("")
self.statusArray.append("")
self.clientId.append(Uservalue as! String)
self.ref.child("Users")
.child(Uservalue as! String)
.child("name")
.observeSingleEvent(of: .value, with: { (snapshot) in
let nameValue = snapshot.value as? String
self.tableArray.insert(nameValue!, at: it)
self.tableArray = self.tableArray.filter {$0 != ""}
self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
self.ref.child("Users")
.child(Uservalue as! String)
.child("lastUpdate")
.observeSingleEvent(of: .value, with: { (snapshot) in
if let nameValue = snapshot.value as? String {
self.statusArray.insert("*", at: it)
self.tableView.reloadData()
} else {
self.statusArray.insert("", at: it)
self.tableView.reloadData()
}
}) { (error) in
print(error.localizedDescription)
}
it += 1
}
}) { (error) in
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
My main issue is that when I get the user's name and their lastUpdate status, the array lists do not match up correctly and the TableView displays the wrong information in terms of which User has submitted their updates. To fix this issue, I tried to use the insert method in my arrays but now the app crashes. Previously, I was using the append method but that leads to the wrong information being displayed in the TableView. I would appreciate it if any of you could help me with this issue.
Note: The App Crashes due to the StatusArray not having the same amount of elements as the TableArray. This is caused by the TableArray having some empty elements with no names in them.
Thanks,
KPS
Edit 1:
for Uservalue in specificValues! {
self.clientId.append(Uservalue as! String)
let user = User()
self.ref.child("Users")
.child(Uservalue as! String)
.observeSingleEvent(of: .value, with: { (snapshot) in
let nameValue = snapshot.value as? NSDictionary
let specNameValue = nameValue?.allKeys
var i = 0
while i < specNameValue!.count {
if specNameValue?[i] as? String == "name" {
user.name = nameValue?.allValues[i] as! String
} else if specNameValue?[i] as? String == "lastUpdate" {
user.status = "*"
} else if specNameValue?[i] as? String != "name" && specNameValue?[i] as? String != "lastUpdate" && specNameValue?[i] as? String != "message" && specNameValue?[i] as? String != "adminMessage" && specNameValue?[i] as? String != "photoURL" {
user.status = ""
}
i += 1
}
}) { (error) in
print(error.localizedDescription)
}
self.tableArray.append(user)
self.tableView.reloadData()
}
The main reason your app is crashing is because in your cell for row you are reloading after loading the first user and the cell expects the statusArray to have elements already.
cell.nameCell.text = tableArray[indexPath.row]
cell.statusCell.text = statusArray[indexPath.row] // fails here I assume
There a few issues going on here that I'll try to address.
You are reloading the table immediately for each child that is iterated through. It would be smart to append elements to each array then once completed display all elements by calling tableView.reloadData()
Are status' independent of the name that you are expecting? If the data is correlated, it would be smart to create a simple Object to house this data and have a single array of data that the tableView will use for it's dataSource
Once your data is fully loaded, you could sort the data accordingly then reload the datasource to solve the issue of pulling data from the server that is out of order. This is why the append(element: ) is simple and useful
Hopefully this helps! It may seem like a bit more work but it would definitely be beneficial to performance, organization and readability for yourself.
Xcode 8.1, Swift 2.3, iOS 10.1, And I use Firebase
I registered notices using firebase. And I am trying show notices on uitableview. viewDidLoad() succesfully connection firebase and get value. But I can not list the incoming data.
First I was getting the error "cellForRowAtIndexPath doesn't work". After, i use forRow & inSection. But now I'm getting the error that I do not know what it means.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'
NoticeViewController.swift
import UIKit
import FirebaseDatabase
import FirebaseAuth
import FirebaseStorage
private let reuseIdentifier = "NoticeViewTable"
class NoticeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var aivLoading: UIActivityIndicatorView!
#IBOutlet weak var noticeTableView: UITableView!
var databaseRef = FIRDatabase.database().reference()
var usersDict = NSDictionary()
var noticesArray = [AnyObject]()
var loggedInUser : AnyObject?
#IBAction func didTapAddNotice(sender: AnyObject) {
let mainStorboard: UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let viewController: UIViewController = mainStorboard.instantiateViewControllerWithIdentifier("AddNoticeView")
self.presentViewController(viewController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.loggedInUser = FIRAuth.auth()?.currentUser
self.aivLoading.startAnimating()
self.databaseRef.child("notice").observeEventType(.Value, withBlock: { (snapshot) in
self.usersDict = snapshot.value as! NSDictionary
self.noticesArray = [AnyObject]()
for (userId, details) in self.usersDict {
let noticeImg = details.objectForKey("noticeImage1") as! String
let profileImg = details.objectForKey("profileImage") as! String
let profileName = details.objectForKey("userName") as! String
let wage = details.objectForKey("wage") as! String
let noticeName = details.objectForKey("noticeName") as! String
if(self.loggedInUser?.uid != userId as? String){
details.setValue(userId, forKey: "uId")
self.noticesArray.append(details)
}
self.noticeTableView?.reloadData()
self.noticeTableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
self.aivLoading.stopAnimating()
}
}) {(error) in
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.noticesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: NoticeViewTableViewCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NoticeViewTableViewCell
let profileImageURL = NSURL(string: self.noticesArray[indexPath.row]["profileImage"] as! String)
let profileImageData = NSData(contentsOfURL: profileImageURL!)
cell.profilePic.image = UIImage(data:profileImageData!)
let noticeImageURL = NSURL(string: self.noticesArray[indexPath.row]["noticeImage!"] as! String)
let noticeImageData = NSData(contentsOfURL: noticeImageURL!)
cell.noticeImage.image = UIImage(data:noticeImageData!)
//add a border and corner radius the images
cell.profilePic.layer.masksToBounds = true
cell.profilePic.layer.cornerRadius = cell.profilePic.frame.size.width/2.0
cell.profilePic.layer.borderWidth = 1.5
let profileName = (self.noticesArray[indexPath.row]["userName"] as? String)!
cell.userName.text = profileName
let noticeName = (self.noticesArray[indexPath.row]["noticeName"] as? String)!
cell.noticeName.text = noticeName
let wage = (self.noticesArray[indexPath.row]["wage"] as? String)!
cell.wage.text = wage
return cell
}
}
There are a lot of mistakes in your code. Any of them could cause the crash.
A row is inserted in the table view even if uid is not valid.
details is appended to the datasource array but inserted at index 0 in the table view
Do not call both reloadData() and insertRowsAtIndexPaths. Delete reloadData()
For other users stumbling upon this question, these errors also arise when trying to update a TableView or CollectionView with no dataSource assigned. Make sure the TableView's dataSource is connected (when using a storyboard or nib) or assigned programmatically.