"Fatal error: Index out of range 2019-08-30 11:01:35.001667-0400 fmcBeta[58563:3478851] Fatal error: Index out of range" - swift

I am creating an events feed, using a table view and Firebase as my database. I am using dateformatter with a style type of full for date and short for time and writing it to my database as a string which is perfect, it writes exactly how i want it to.
However, when i try to read the data from firebase and display it on my textlabel in the tableview cell i get the following error.
Error:
"Fatal error: Index out of range
2019-08-30 11:01:35.001667-0400 fmcBeta[58563:3478851] Fatal error: Index out of range"
Any help would be greatly appreciated i am self learning and fairly new to swift.
This is my table view cell:
class EventsTableViewCell: UITableViewCell {
#IBOutlet weak var eventLocation: UILabel!
#IBOutlet weak var eventDate: UILabel!
#IBOutlet weak var eventTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This is my viewcontoller with tableview protocols:
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]()
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)
self.tableView.reloadData()
})
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
cell.eventTitle.text! = eventsTitles[indexPath.row]
cell.eventDate.text! = eventTimestamps[indexPath.row]
cell.eventLocation.text! = eventsLocations[indexPath.row]
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
return cell
}
}
This is how i'm writing the data to Firebase
#IBAction func saveEventsButton(_ sender: Any) {
let eventsDates = DateFormatter.localizedString(from: eventDateSelector.date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.short) as String
print(eventsDates.description)
let eventSaved:[String: Any] = ["eventdate": eventsDates,"eventtitle":eventsTitleTextField.text!,"eventlocation":eventsLocation.text!]
eventsRef.child("Church Events").childByAutoId().setValue(eventSaved)
self.dismiss(animated: true, completion: nil)
}
}

Related

XCode 12/Swift 4 Custom Cells not displaying on UI Table Cell View

Ok so, I am trying to make a custom table that has a news feed from newsapi, from my debugging: the api calls and such get made and the data is acessed, its just that it doesnt display on the table, it shows up as a blank table.
Here is the code:
This is from the "first view controller" as I am using the tabbed template
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var articles: [Article]? = []
override func viewDidLoad() {
super.viewDidLoad()
fetchArticles()
}
func fetchArticles(){
let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/top-headlines?country=us&?category=business&apiKey=sorrynotgivingmykey")!)
let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error) in
if error != nil{
print(error)
return
}
self.articles = [Article]()
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let articlesFromJson = json["articles"] as? [[String: AnyObject]]{
for articlesFromJson in articlesFromJson{
let article = Article()
if let title = articlesFromJson["title"] as? String, let desc = articlesFromJson["description"] as? String, let url = articlesFromJson["url"] as? String, let imageToUrl = articlesFromJson["urlToImage"] as? String, let date = articlesFromJson["publishedAt"] as? String{
article.headline = title
article.desc = desc
article.url = url
article.imageUrl = imageToUrl
article.date = date
// print(article.date)
// print(article.headline)
}
self.articles?.append(article)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch let error{
print(error)
}
}
task.resume()
// print(articles)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "worklmao", for: indexPath) as! ArticleCell
cell.title.text = self.articles?[indexPath.item].headline
cell.desc.text = self.articles?[indexPath.item].desc
cell.date.text = self.articles?[indexPath.item].date
print("lol lmao hahax help fuck shit")
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
1
}
}
And this is the cell classes I used for the articles
import UIKit
class ArticleCell: UITableViewCell {
#IBOutlet weak var date: UILabel!
#IBOutlet weak var desc: UILabel!
#IBOutlet weak var title: UILabel!
#IBOutlet weak var ImgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This is the article class
import UIKit
class Article: NSObject {
var headline: String?
var desc: String?
var url: String?
var date: String?
var imageUrl: String?
}
and bare in mind I did setup the class for the cell properly(at least I think
Still, this is what I get:
Don't forget to connect dataSource and delegate for tableView.
Change your tableView outlets to this:
#IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
}
}
Some points:
You don't have to declare articles array as optional. Simply do this :
var articles = [Article]()
Try to learn about codables for JSON parsing.

Updating Realm through a custom button on the UITableViewCell

I have a tableview of "Books" that are stored in Realm. I want to set the "CurrentBook" property to "True" when hitting a button on a custom UITableViewCell.
I believe my error has something to do with getting the correct book value in "func selectCurrentBook", when I use an optional like below nothing happens.
#objc func selectCurrentBook(sender: UIButton) {
try! realm.write {
book?.currentlyReading = true
}
}
When I don't use an optional for book and use book.currentlyReading = true I get the error "Unexpectedly found nil while implicitly unwrapping an Optional value:"
Am I incorrectly passing the book value somewhere? I can't seem to find out how. Maybe I'm delegating wrong?
My TableViewCell is:
import UIKit
import RealmSwift
protocol MyBooksDelegate {
func currentlyReadingButton()
}
class MyBooksTableViewCell: UITableViewCell {
let realm = try! Realm()
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var authorLabel: UILabel!
#IBOutlet weak var smallThumbnailImageView: UIImageView!
#IBOutlet weak var currentlyReadingButton: UIButton!
#IBAction func currentlyReadingButton(_ sender: Any) {
}
private var book: Book!
func loadImage(smallThumbnailURL: String) {
let imageURL = URL(string: smallThumbnailURL ?? "")
smallThumbnailImageView.sd_setImage(with: imageURL)
}
func configureCell(book: Book, delegate: MyBooksDelegate?) {
titleLabel.text = book.bookTitle
authorLabel.text = book.bookAuthor
loadImage(smallThumbnailURL: book.bookSmallThumbnailImageURL)
currentlyReadingButton.addTarget(self, action: #selector(selectCurrentBook(sender:)), for: .touchUpInside)
}
#objc func selectCurrentBook(sender: UIButton) {
try! realm.write {
book?.currentlyReading = true
}
}
}
My View Controller with TableView is :
import SwiftyJSON
import RealmSwift
class BooksViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var myBooksTableView: UITableView!
let realm = try! Realm()
var books: Results<Book>?
// Search Bar Properties
var searchParameter = "intitle"
var booksArray: [Book] = []
override func viewDidLoad() {
super.viewDidLoad()
loadBooks()
// Setting up the TableView
self.myBooksTableView.delegate = self
self.myBooksTableView.dataSource = self
self.myBooksTableView.rowHeight = 120.0
// Setup Title
title = "My Books"
// navigationController?.navigationBar.prefersLargeTitles = true
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.barStyle = .black
loadBooks()
}
func loadBooks() {
books = realm.objects(Book.self).sorted(byKeyPath: "DateCreated", ascending: false)
myBooksTableView.reloadData()
}
// TABLEVIEW
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books?.count ?? 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "MyBooksTableViewCell", for: indexPath) as? MyBooksTableViewCell {
cell.configureCell(book: (books?[indexPath.row])!, delegate: self as? MyBooksDelegate)
// cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "myBooksTOMyBooksDetail", sender: self)
myBooksTableView.deselectRow(at: indexPath, animated: true)
}
And my Book Model is:
class Book: Object {
#objc dynamic var bookTitle: String!
#objc dynamic var bookAuthor: String!
#objc dynamic var bookSmallThumbnailImageURL: String!
#objc dynamic var bookThumbnailImageURL: String!
#objc dynamic var bookDescription: String!
#objc dynamic var bookISBN_13: String!
#objc dynamic var currentlyReading = false
#objc dynamic var DateCreated = Date()
#objc dynamic var WordID = UUID().uuidString
// words
let words = List<Word>()
override static func primaryKey() -> String? {
return "WordID"
}
}
The most compatible syntax is
currentlyReadingButton.addTarget(self, action: #selector(selectCurrentBook), for: .touchUpInside)
and
#objc func selectCurrentBook(_ sender: UIButton) {
However as the cell is custom anyway I'd prefer an IBAction over target/action
And the protocol MyBooksDelegate seems to be unused.
Side note:
Force unwrap the cell
let cell = tableView.dequeueReusableCell(withIdentifier: "MyBooksTableViewCell", for: indexPath) as! MyBooksTableViewCell
A crash – with report – reveals a design mistake which can be fixed instantly. With the if let you'll see nothing and have no clue why.
Update:
The crash occurs because you don't set book in the cell, add the first line after the {
func configureCell(book: Book, delegate: MyBooksDelegate?) {
self.book = book
titleLabel.text = book.bookTitle
...

How can I get user to input text in a text field inside a xib cell in swift

I have created a xib cell with two textfields. The textfield are connected as IBoutlets to the xib swift file. The xib cell is registered on the view controller as a Nib. When I run the app on a simulator I cannot get the keyboard to show up. Secondly, the textfields are not editable at all, that is the cursor doesn't even show. I would like to get help with this as I have tried using a label the same thing happens. I'm just not sure how to fix this one. I'm not getting errors on build. I have installed IQKeyboardManager from cocoapods. Thanks in advance.
Heres the code:
import UIKit
class DictionaryCell: UITableViewCell {
#IBOutlet weak var DictBubble: UIView!
#IBOutlet weak var DictSymbolTextfield: UITextField!
#IBOutlet weak var SymbolMeaningTextfield: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Here is the view controller code:
import UIKit
import Firebase
class PersonalDreamDictionaryViewController: UIViewController, UITextViewDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var dictionaryTextfield: UITextField!
let db = Firestore.firestore()
var dreamDictionary: [DreamDictionary] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
title = K.Dictionary.appName
tableView.register(UINib(nibName: K.Dictionary.cellNibName, bundle: nil), forCellReuseIdentifier:
K.Dictionary.cellIdentifier)
loadDictionaryList()
}
func loadDictionaryList() {
db.collection(K.Fstore1.collectionName)
.order(by: K.Fstore1.date)
.addSnapshotListener{ (QuerySnapshot, error) in
self.dreamDictionary = []
if let e = error {
print("There was an issue retrieving data from Firestore. \(e)")
} else {
if let snapshotDocuments = QuerySnapshot?.documents {
for doc in snapshotDocuments {
//print(doc.data())
let data = doc.data()
if let symbolRetrieved = data[K.Fstore1.symbol] as? String, let meaningRetrieved = data[K.Fstore1.meaning] as? String {
let newDictList = DreamDictionary(mysymbol: symbolRetrieved, mymeaning: meaningRetrieved)
self.dreamDictionary.append(newDictList)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
}
}
}
extension PersonalDreamDictionaryViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dreamDictionary.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dictCell = tableView.dequeueReusableCell(withIdentifier: K.Dictionary.cellIdentifier, for: indexPath)
as! DictionaryCell
if let symbolInput = dictCell.DictSymbolTextfield.text, let meaningInput = dictCell.SymbolMeaningTextfield.text { db.collection(K.Fstore1.collectionName).addDocument(data: [
K.Fstore1.symbol: symbolInput,
K.Fstore1.meaning: meaningInput,
K.Fstore1.date: Date().timeIntervalSince1970
]) { (error) in
if let e = error {
print("There was an issue saving data to firesore, \(e)")
} else {
print("Successfully saved data.")
}
}
}
return dictCell
}
}
extension PersonalDreamDictionaryViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
print(indexPath.row)
}
}

Unable to simultaneously satisfy constraints error whats causing this?

ca someone help me with this
import UIKit
import Firebase
class aboutmeViewController: UIViewController , UITableViewDelegate,UITableViewDataSource {
var refrelation : DatabaseReference!
#IBOutlet weak var me: UITableView!
var relationList = [aboutmeModel] ()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return relationList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
as! ViewControllerTableViewCell
let relation: aboutmeModel
relation = relationList[indexPath.row]
cell.fname.text = relation.firstname
cell.lname.text = relation.lastname
return cell
}
override func viewDidLoad() {
refrelation.observe(DataEventType.value, with: {(snapshot)in
if snapshot.childrenCount>0{
self.relationList.removeAll()
for relations in snapshot.children.allObjects as![DataSnapshot]{
let relationObject = relations.value as? [String: AnyObject]
let firstname = relationObject? ["firstName"]
let lastname = relationObject? ["lastname"]
let pob = relationObject?["dob"]
let age = relationObject?["relation"]
let id = relationObject?["id"]
let relation = aboutmeModel (id: id as!
String?, firstname: firstname
as! String?, lastname: lastname as! String?, relation: age as! String?,
dob: pob as! String?)
self.relationList.append(relation)
}
self.me.reloadData()
}
})
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
this is my subclass for the table view
import UIKit
class ViewControllerTableViewCell: UITableViewCell {
#IBOutlet weak var fname: UILabel!
#IBOutlet weak var age: UILabel!
#IBOutlet weak var placeofbirth: UILabel!
#IBOutlet weak var lname: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
what i want my app to do is to fetch the data from the database and display it in the aboutmeviewcontroller, however the app wont even run, i tried following a tutorial on youtube https://www.youtube.com/watch?v=ge56yTgnjKs&t=263s thats the link, however I keep on getting an error, can someone please help!
this is the error im getting.
"Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want."

how to pass data retrieve from firebase in Table VIew Controller to View Controller

I am building a car sharing IOS App prototype. My app is link to firebase, i can retrieve and display journey data in a table view but when trying to pass the data in another view controller the data do not display. Below are my table View controller and view controllers source codes.
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myIndex = 0
var journeyList = [journeyModel]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return journeyList.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
// defining firebase reference var
var refjourney: DatabaseReference!
#IBOutlet weak var journeyTable: UITableView!
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath as IndexPath) as! journeySearchTableViewCell
var journe: journeyModel
journe = journeyList[indexPath.row]
print(journe.start!, journe.destination!, journe.date!, journe.driverName!)
cell.driverNameLabel.text = journe.driverName
cell.startLabel.text = journe.start
cell.destinationLabel.text = journe.destination
cell.dateLabel.text = journe.date
return cell
}
At this point the app functions correctly only faces issues when passing the data to another view controller
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Journey").observe(.value, with: { (snapshot) in
if snapshot.childrenCount > 0 {
self.journeyList.removeAll()
for journey in snapshot.children.allObjects as! [DataSnapshot] {
let journeyObject = journey.value as? [String: AnyObject]
let start = journeyObject?["startingPoint"]
let destination = journeyObject?["destinationPoint"]
let driverName = journeyObject?["driverName"]
let date = journeyObject?["tripDate"]
let id = journeyObject?["id"]
let journey = journeyModel(destination: destination as! String?, driverName: driverName as! String?, start: start as! String?, date: date as! String?, uid: id as! String?)
self.journeyList.append(journey)
}
self.journeyTable.reloadData()
}
})
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "logged", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var bsVC: bookSetViewController = segue.destination as! bookSetViewController
}
#IBAction func backButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
import UIKit
class bookSetViewController: UIViewController {
var getStart = String()
var getStop = String()
var getDate = String()
var getDriver = String()
#IBOutlet weak var startingLabel: UILabel!
#IBOutlet weak var stopingLabel: UILabel!
#IBOutlet weak var daterLabel: UILabel!
#IBOutlet weak var driveLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
startingLabel.text! = getStart
stopingLabel.text! = getStop
daterLabel.text! = getDate
driveLabel.text! = getDriver
}
}
import UIKit
class journeySearchTableViewCell: UITableViewCell {
#IBOutlet weak var startLabel: UILabel!
#IBOutlet weak var destinationLabel: UILabel!
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var driverNameLabel: UILabel!
}
import UIKit
class journeyModel: NSObject {
var driverName: String?
var start: String?
var destination: String?
var date: String?
var uid: String?
init(destination: String?, driverName: String?, start: String?, date: String?, uid: String?) {
self.driverName = driverName
self.start = start
self.destination = destination
self.date = date
self.uid = uid
}
}
First things, first - don't share the whole project, just the bits that are needed.
The whole point of the prepare(for segue... is to get a handle to the new controller, and assign the values you need to pass over.
You will need to keep a track of which journey you're interested in. There are many ways to do this, but the easiest might be to extend what you do on the click row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// assume you have defined journeySelected as a class-level instance of journeyModel
journeySelected = journeyModel[indexPath.row]
performSegue(withIdentifier: "logged", sender: self)
}
and then
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var bsVC: bookSetViewController = segue.destination as! bookSetViewController
bsVC.getStart = journeySelected.start
// and for all the other fields
}