This app allows Rider to request a ride and driver to accept the request. In this tableview are the rides the riders (2) have requested.
Unable to update tableviewcells.
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAuth
import FirebaseCore
import CoreLocation
class RequestsTVC: UITableViewController {
var geoCoder : CLGeocoder?
var rideRequests = [FIRDataSnapshot]()
let ref = FIRDatabase.database().reference() //(withPath: "RideRequests")
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.geoCoder = CLGeocoder()
self.navigationController?.isNavigationBarHidden = false
/*
.observe is called whenever anything changes in the Firebase -
It's also called here in viewDidLoad().
It's always listening.
*/
ref.child("drivers").child("RideRequests").observe(FIRDataEventType.value, with: { snapshot in
self.rideRequests.removeAll()
for item in snapshot.children{
self.rideRequests.append(item as! FIRDataSnapshot)
}
self.rideRequests.reverse()
self.tableView.reloadData()
})
DispatchQueue.main.async (execute: { () -> Void in
self.tableView.reloadData()
})
} // func viewDidLoad()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rideRequests.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RequestsCell", for: indexPath)
let usernameLabel = cell.contentView.viewWithTag(2) as! UILabel
let locationLbl = cell.contentView.viewWithTag(1) as! UILabel
let destinationLbl = cell.contentView.viewWithTag(3) as! UILabel
let request = self.rideRequests[indexPath.row]
let username = request.childSnapshot(forPath: "username")
let destLatString = request.childSnapshot(forPath: "destLat").value
let destLat = Double(destLatString as! String)
let destLongString = request.childSnapshot(forPath: "destLong").value
let destLong = Double(destLongString as! String)
let usernameText = username.value as! String
let location = RiderVC.instance.locationManager.location
let destination = CLLocation(latitude: destLat!, longitude: destLong!)
usernameLabel.text = usernameText
locationLbl.text = "Waiting ..."
destinationLbl.text = "Loading ... "
// LOCATION and DESTINATION
geoCoder?.reverseGeocodeLocation(location!, completionHandler: { (data, error) -> Void in
guard let placeMarks = data as [CLPlacemark]! else {
return
}
let loc: CLPlacemark = placeMarks[0]
let addressDict : [NSString: NSObject] = loc.addressDictionary as! [NSString: NSObject]
let addrList = addressDict["FormattedAddressLines"] as! [String]
print(addrList)
locationLbl.text = addrList[0]
// THAT'S THE FIRST BIT DONE
// THIS IS STILL INSIDE THE COMPELTION HANDLER
// NOW DO DESTINATION
// DESTINATION
self.geoCoder?.reverseGeocodeLocation(destination, completionHandler: { (data, error) -> Void in
guard let placeMarks = data as [CLPlacemark]! else {
return
}
let loc: CLPlacemark = placeMarks[0]
let addressDict : [NSString: NSObject] = loc.addressDictionary as! [NSString: NSObject]
let addrList = addressDict["FormattedAddressLines"] as! [String]
destinationLbl.text = addrList[0]
})
})
return cell
}
**Screen shot of table view not updating after 1st cell **
make sure you reload tableview in main queue in with parameter closure.
ref.child("drivers").child("RideRequests").observe(FIRDataEventType.value, with: { snapshot in
self.rideRequests.removeAll()
for item in snapshot.children{
self.rideRequests.append(item as! FIRDataSnapshot)
}
self.rideRequests.reverse()
DispatchQueue.main.async (execute: { () -> Void in
self.tableView.reloadData()
})
})
The callbacks from Geocoder are asynchronous and you can't simply change the values in the table cells by updating the label values inside the callback - you have to inform the table view to reload the cell in order to update it.
So, you need to pull out the GeoCoder lookups from inside tableView:cellForRowAt and move them into a loop in either viewDidLoad or viewWillAppear. The final values should form part of you model.
Inside the callbacks for the GeoCoder you would then tell the table view to reload each individual cell calling tableView.reloadRows with a single value array.
Related
I have a tableview loading data from firebase database. When I open my app the data does not populate. when I create a new post I can see the tableview cells modifying like changed were made but the post doesn't populate. I can't figure it out.
import UIKit
import FirebaseAuth
import FirebaseDatabase
class EventsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var eventsRef: DatabaseReference?
var eventsDatabaseHandle:DatabaseHandle?
var eventsTitles = [String]()
var eventTimestamps = [String]()
var eventsLocations = [String]()
var eventsImages = [UIImage]()
#IBOutlet weak var addEventsButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
adminAuth()
eventsRef = Database.database().reference()
tableView.reloadData()
tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
tableView.delegate = self
tableView.dataSource = self
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { (snaphot) in
let eventPost = snaphot.value as! [String: Any]
self.eventTimestamps.append(eventPost["eventdate"] as! String)
self.eventsTitles.append(eventPost["eventtitle"] as! String)
self.eventsLocations.append(eventPost["eventlocation"] as! String)
let task = URLSession.shared.dataTask(with: URL(string: eventPost["ImageUrl"] as! String)!) {(data, response, error) in
if let image: UIImage = UIImage(data: data!) {
self.eventsImages.append(image)
}
}
self.tableView.reloadData()
task.resume()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsImages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let image = eventsImages[indexPath.row]
cell.flyerImages.image! = image
cell.eventTitle.text! = eventsTitles[indexPath.row]
cell.eventDate.text! = eventTimestamps[indexPath.row]
cell.eventLocation.text! = eventsLocations[indexPath.row]
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
tableView.reloadData()
return cell
}
func adminAuth() {
if (Auth.auth().currentUser!.displayName != "Neil Leon") {
self.addEventsButton.tintColor = UIColor.clear
self.addEventsButton.isEnabled = false
}
else{
self.addEventsButton.isEnabled = true
}
}
}
image of empty tableview
]
So the code below is not tested as I don't have firebase setup currently.
However, observing childAdded... the documentation says it will pass all of the current records in the database at first and will then just post new additions. So all you need to do is loop through them, setup your tableView data source and reload the table.
Rather than use multiple arrays for values I've created an array of ChurchEvent objects instead.
struct ChurchEvents {
let title: String
let location: String?
let date: Date?
let imageUrlString: String?
init(dict: [String: Any]) {
self.title = dict["title"] as String
self.location = dict["location"] as? String
// etc
}
}
var events = [ChurchEvents]()
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { snapshot in
let list = snapshot.value as? [[String : AnyObject]]
let newEvents = list.map { ChurchEvent(dict: $0) }
events.append(newEvents)
tableView.reloadData()
}
Other improvements you could make:
class EventsTableViewCell: UICollectionViewCell {
func configure(with event: ChurchEvent {
eventDate.text = event.date
eventTitle.text = event.title
eventLocation.text = event.location
// etc
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let event = events[indexPath.row]
cell.configure(with: event)
return cell
}
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()
}
})
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()
}
}
}
})
}
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.