Display last message in chat with firestore - ios

How I can get and display last message in my chat?
For test, I created four users with test messages. Now I can display only last message for all users. I mark red color.
Also I use firebase to save messages and create channels.
Struct in firebase look like this:
- Chats
- channel id
- document data (then be stored ID and NAME of channel)
- collection thread
- documents data (then be stored MESSAGES)
My struct in channel:
struct Channel {
let id: String?
let name: String
init(name: String) {
id = nil
self.name = name
}
init?(document: DocumentSnapshot) {
let data = document.data()!
guard let name = data["name"] as? String else {
return nil
id = document.documentID
self.name = name
}
}
extension Channel: DatabaseRepresentation {
var representation: [String : Any] {
var rep = ["name": name]
if let id = id {
rep["id"] = id
}
return rep
}
}
And my struct message, I use MessageKit:
struct Message: MessageType {
let id: String?
let content: String
let sentDate: Date
let sender: SenderType
var kind: MessageKind {
if let image = image {
return .photo(ImageMediaItem.init(image: image))
} else {
return .text(content)
}
}
var messageId: String {
return id ?? UUID().uuidString
}
var image: UIImage? = nil
var downloadURL: URL? = nil
init(profile: Profile, content: String) {
sender = Sender(id: profile.id, displayName: profile.name)
self.content = content
sentDate = Date()
id = nil
}
init?(document: QueryDocumentSnapshot) {
let data = document.data()
guard let sentDate = (data["created"] as? Timestamp)?.dateValue() else {
return nil
}
guard let senderID = data["senderID"] as? String else {
return nil
}
guard let senderName = data["senderName"] as? String else {
return nil
}
id = document.documentID
self.sentDate = sentDate
sender = Sender(id: senderID, displayName: senderName)
if let content = data["content"] as? String {
self.content = content
downloadURL = nil
} else if let urlString = data["url"] as? String, let url = URL(string: urlString) {
downloadURL = url
content = ""
} else {
return nil
}
}
}
extension Message: DatabaseRepresentation {
var representation: [String : Any] {
var rep: [String : Any] = [
"created": sentDate,
"senderID": sender.senderId,
"senderName": sender.displayName
]
if let url = downloadURL {
rep["url"] = url.absoluteString
} else {
rep["content"] = content
}
return rep
}
}
For load my chennels I use code below:
fileprivate func observeQuery() {
guard let query = query else { return }
listener = query.addSnapshotListener { (snapshot, error) in
guard let snapshot = snapshot else {
print("Error listening for channel updates: \(error?.localizedDescription ?? "No error")")
return
}
snapshot.documentChanges.forEach { (change) in
self.handleDocumentChange(change)
}
}
}
private func handleDocumentChange(_ change: DocumentChange) {
guard let channel = Channel(document: change.document) else {
return
}
switch change.type {
case .added:
addChannelToTable(channel)
case .modified:
updateChannelInTable(channel)
case .removed:
removeChannelFromTable(channel)
}
}
private func addChannelToTable(_ channel: Channel) {
guard !channels.contains(channel) else {
return
}
channels.append(channel)
channels.sort()
guard let index = channels.index(of: channel) else {
return
}
tableView.insertRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
private func updateChannelInTable(_ channel: Channel) {
guard let index = channels.index(of: channel) else {
return
}
channels[index] = channel
tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
private func removeChannelFromTable(_ channel: Channel) {
guard let index = channels.index(of: channel) else {
return
}
channels.remove(at: index)
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
I think need update my Channel struct. But how to do it?
And how to correct load and display last message from firebase?
If need more info pls tell me, I will update my question.

If the question is how to get only the last message from Firestore, you need to define how to determine what the last message is. That's usually done via a timestamp - the latest timestamp will be the last message.
The structure in the question is a little unclear so let me provide a simple example.
messages //collection
document_0 //documentID auto-generated
msg: "Last Message"
timestamp: "20191201"
document_1
msg: "First message"
timestamp: "20190801"
document_2
msg: "A message in the middle"
timestamp: "20191001"
As you can see, no matter what order they are written to Firestore, it's clear that the one with the latest timestamp (20191201 ) is the last message.
To get the last message we need a query that does two things:
1) Query the messages node, sort descending, which will put the last message 'at the top'
2) Limit the query to 1, which will get that message.
func readLastMessage() {
let ref = Firestore.firestore().collection("messages").order(by: "timestamp", descending: true).limit(to: 1)
ref.getDocuments(completion: { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
if let doc = snapshot.documents.first {
let docID = doc.documentID
let msg = doc.get("msg")
print(docID, msg)
}
})
}
and the output
Last Message
The above code gets the last message but could be expanded upon by adding an observer instead of getDocuments in the same fashion that will notify the app when there's a new last message.

Related

Unexpectedly found nil while unwrapping... MessageKit

I have a struct set up for Messages and each time I got to load messages in app, I receive an unexpectedly found nil error on this line of code -->
var chatPartnerId: String {
return isFromCurrentUser ? toID! : fromID! // where I get the error
}
I can't figure out what Im doing wrong here at all.
Here's the class setup:
struct Message: MessageType {
let id: String?
var messageId: String {
return id ?? UUID().uuidString
}
var content: String?
var toID: String?
var fromID: String?
var isFromCurrentUser = Bool()
var chatPartnerId: String {
return isFromCurrentUser ? toID! : fromID!
}
let sentDate: Date
let sender: SenderType
var image: UIImage?
var downloadURL: URL?
var kind: MessageKind {
if let image = image {
let mediaItem = ImageMediaItem(image: image)
return .photo(mediaItem)
} else {
return .text(content ?? "")
}
}
init(user: User, content: String, fromID: String, toID: String) {
sender = Sender(senderId: user.uid!, displayName: user.name!)
self.content = content
self.fromID = fromID
self.toID = toID
sentDate = Date()
id = nil
}
init(user: User, image: UIImage) {
sender = Sender(senderId: user.uid!, displayName: user.name!)
self.image = image
content = ""
fromID = ""
toID = ""
sentDate = Date()
id = nil
}
init?(document: QueryDocumentSnapshot) {
let data = document.data()
guard
let sentDate = data["created"] as? Timestamp,
let senderId = data["senderId"] as? String,
let fromID = data["fromID"] as? String,
let toID = data["toID"] as? String,
let senderName = data["senderName"] as? String
else {
return nil
}
id = document.documentID
self.sentDate = sentDate.dateValue()
sender = Sender(senderId: senderId, displayName: senderName)
self.isFromCurrentUser = fromID == Auth.auth().currentUser?.uid
if let content = data["content"] as? String {
self.content = content
downloadURL = nil
} else if let urlString = data["url"] as? String, let url = URL(string: urlString) {
downloadURL = url
content = ""
} else {
return nil
}
}
}
// MARK: - DatabaseRepresentation
extension Message: DatabaseRepresentation {
var representation: [String: Any] {
var rep: [String: Any] = [
"created": sentDate,
"senderId": sender.senderId,
"fromID": fromID,
"toID": toID,
"senderName": sender.displayName
]
if let url = downloadURL {
rep["url"] = url.absoluteString
} else {
rep["content"] = content
}
return rep
}
}
// MARK: - Comparable
extension Message: Comparable {
static func == (lhs: Message, rhs: Message) -> Bool {
return lhs.id == rhs.id
}
static func < (lhs: Message, rhs: Message) -> Bool {
return lhs.sentDate < rhs.sentDate
}
}
Both toID and fromID are optionals and may be nil. Avoid force unwrapping the optional (and actually avoid force unwrapping anything else, with very rare exceptions), like you do in the problematic statement.
Instead, you can:
Don't be afraid to return an optional:
var chatPartnerId: String? { // <-- returns optional
return isFromCurrentUser ? toID : fromID
}
In many cases it's much better to deal with the nil as a condition that helps you understand the state of the app. For example nil may mean you should skip the processing of such message.
You can return a default bogus ID, or an empty string:
var chatPartnerId: String {
guard let id = isFromCurrentUser ? toID : fromID else {
return "" // <-- returns bogus ID
}
return id
}
You can change the property to be required:
var toID: String // <-- not optional
var fromID: String // <-- not optional
Looking at all of your inits I see none of them allows these paramters to be nil. So you don't need to make them optional.

How do I take the name of the Firebase document? Swift

How do I take the name of the Firebase document, directly from the information of the logged in user?
Basically I have a user collection and a Degree Course collection.
When I use the func
GetCorsodiLaurea
I don't want to manually insert the document name in .document ("")
But I would like to automatically take the name of the document directly from the user's info
The field that declares which course is connected to the user is "TipoCorso".
As you can see in the Degree Courses collection there is the value of the "TipoCorso" field
Here is the code of the function and a screen of the Firebase Database:
import SwiftUI
import Firebase
import FirebaseFirestoreSwift
import FirebaseDatabase
class ProfileViewModel : ObservableObject{
#Published var userInfo = UserModel(Nome: "", Cognome: "", photoURL: "", Nomeintero: "", Corsodilaurea: "", Tipocorso: "")
#Published var userDegree = userDegreeModel(Name: "", TotalSubjects: "")
var ref = Firestore.firestore()
let uid = Auth.auth().currentUser!.uid
let db = Firestore.firestore()
init() {
fetchUser()
GetCorsodiLaurea()
}
func fetchUser() {
ref.collection("users").document(uid).getDocument { [self] (doc, err) in guard let user = doc else { return }
let Nome = user.data()?["Nome"] as! String
let Cognome = user.data()?["Cognome"] as! String
let photoURL = user.data()?["photoURL"] as! String
let Nomeintero = user.data()?["Nomeintero"] as! String
let Tipocorso = user.data()?["Tipocorso"] as! String
let Corsodilaurea = user.data()?["Corsodilaurea"] as! String
DispatchQueue.main.async {
self.userInfo = UserModel(Nome: Nome, Cognome: Cognome, photoURL: photoURL, Nomeintero: Nomeintero, Corsodilaurea: Corsodilaurea, Tipocorso: Tipocorso) }
}
}
func GetCorsodiLaurea() {
db.collection("DegreeCourses").document(self.userInfo.Tipocorso).getDocument { [self] (doc, err) in guard let DegreeCourses = doc else { return }
let Name = DegreeCourses.data()?["Name"] as! String
let TotalSubjects = DegreeCourses.data()?["TotalSubjects"] as! String
// [END doc_reference]
// [END collection_reference]
DispatchQueue.main.async {
self.userDegree = userDegreeModel(Name: Name, TotalSubjects: TotalSubjects)
}
}
}
}
User
DegreeCourses
When you call the fetchUeser() function it looks like you are populating the UserModel with the specific user's Tipocorso.
So in the GetCorsodiLaurea function you can call Tipocorso member in userInfo variable.
ref.collection("DegreeCourses").document(self.userInfo.Tipocorso).getDocument { [self] (doc, err) in guard let DegreeCourses = doc else { return }
Edit: You are most likely getting the error because the fetchUsers() function hasn't completed fully (as it is waiting for Firebase to respond) but the execution has already proceeded to the GetCorsodiLaurea() function.
To fix this add, a escaping closure to the fetchUsers() function and call the GetCorsodiLaurea() function in the closure. This way, the compiler won't try and execute the functions asynchronously.
import SwiftUI
import Firebase
import FirebaseFirestoreSwift
import FirebaseDatabase
class ProfileViewModel : ObservableObject{
#Published var userInfo = UserModel(Nome: "", Cognome: "", photoURL: "", Nomeintero: "", Corsodilaurea: "", Tipocorso: "")
#Published var userDegree = userDegreeModel(Name: "", TotalSubjects: "")
var ref = Firestore.firestore()
let uid = Auth.auth().currentUser!.uid
let db = Firestore.firestore()
init() {
//GetCorsodilaurea() will only get called after fetchUser() is complete
fetchUser(completion: {
GetCorsodiLaurea()
})
}
func fetchUser(completion: #escaping () -> Void)) {
ref.collection("users").document(uid).getDocument { [self] (doc, err) in guard let user = doc else { return }
let Nome = user.data()?["Nome"] as! String
let Cognome = user.data()?["Cognome"] as! String
let photoURL = user.data()?["photoURL"] as! String
let Nomeintero = user.data()?["Nomeintero"] as! String
let Tipocorso = user.data()?["Tipocorso"] as! String
let Corsodilaurea = user.data()?["Corsodilaurea"] as! String
//don't do this async
self.userInfo = UserModel(Nome: Nome, Cognome: Cognome, photoURL: photoURL, Nomeintero: Nomeintero, Corsodilaurea: Corsodilaurea, Tipocorso: Tipocorso)
completion()
}
}
func GetCorsodiLaurea() {
db.collection("DegreeCourses").document(self.userInfo.Tipocorso).getDocument { [self] (doc, err) in guard let DegreeCourses = doc else { return }
let Name = DegreeCourses.data()?["Name"] as! String
let TotalSubjects = DegreeCourses.data()?["TotalSubjects"] as! String
// [END doc_reference]
// [END collection_reference]
DispatchQueue.main.async {
self.userDegree = userDegreeModel(Name: Name, TotalSubjects: TotalSubjects)
}
}
}

Firestore iOS - Delete function in UITableview

I am trying to delete a document from Firestore that appears as a UITableViewCell on my UITableView using the swipe to delete function.
var sourseArray : [Sourse] = []
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let sourseItem = sourseArray[indexPath.row]
Firestore.firestore().collection("sourses").document(sourseItem.documentId).delete(completion: { (error) in
if let error = error {
debugPrint("Could not delete thought: \(error.localizedDescription)")
}
})
}
}
When I swipe and hit the "delete" button. This error appears
*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid document reference.
Document references must have an even number of segments, but sourses
has 1'
I adjusted the "rules" of my Firestore database to allow for deleting.
After some research it appears that I'm not referencing the correct document somehow. Is it a bad reference or is the error something else?
Also here is what a "sourse" model is.
class Sourse {
private(set) var name: String!
private(set) var content: String!
private(set) var timeStamp: Date!
private(set) var documentId: String!
private(set) var userId: String!
init(name: String, timeStamp: Date, content: String, documentId: String, userId: String) {
self.name = name
self.content = content
self.timeStamp = timeStamp
self.documentId = documentId
self.userId = userId
}
}
//EDIT
I just noticed I did not add a documentId when creating a new sourse. As seen below.
#IBAction func addSourse(_ sender: Any) {
Firestore.firestore().collection(SOURSES_REF).addDocument(data: [
NAME : sourseTextField.text ?? "",
CONTENT : contentTextField.text ?? "",
TIMESTAMP : FieldValue.serverTimestamp(),
USERNAME : Auth.auth().currentUser?.displayName ?? "",
USER_ID : Auth.auth().currentUser?.uid ?? ""
]) { (err) in
if let err = err {
debugPrint("Error adding document document: \(err)")
} else {
self.navigationController?.popViewController(animated: true)
}
}
}
However, that is also the way it was in my tutorial and it worked fine.
///Edit 2 To show how I am fetching it.
func loadData() {
db.collection("sourses").getDocuments() { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let name = data["name"] as? String ?? ""
let content = data["content"] as? String ?? ""
let timeStamp = data["timeStamp"] as? Date ?? Date()
let documentId = data["documentId"] as? String ?? ""
let userId = data["userId"] as? String ?? ""
let newSourse = Sourse(name:name, timeStamp: timeStamp, content:content, documentId: documentId, userId: userId)
self.sourseArray.append(newSourse)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
}
Answer: The function to swipe to delete was correct the whole time. As Dopapp pointed out, I was incorrectly loading my document.Id.
If the problem is indeed that your documentId is wrong, you may be retrieving it incorrectly. Here is a quick example of how to create your object with the right id:
collection.addSnapshotListener { (snapshot, error) in
if let documents = snapshot?.documents {
for document in documents {
guard let data = document.data() else { continue }
let id = document.documentID
let sourseItem = Sourse(name: data['name'], ..., documentId: id, ...)
// use sourseItem
}
}
}
If you are doing something similar, I would check if the document ids are being swapped between objects. If so, that might suggest an async-related problem.
For your particular case, loadData() should look like this:
func loadData() {
db.collection("sourses").getDocuments() { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let name = data["name"] as? String ?? ""
let content = data["content"] as? String ?? ""
let timeStamp = data["timeStamp"] as? Date ?? Date()
let documentId = document.documentID
let userId = data["userId"] as? String ?? ""
let newSourse = Sourse(name:name, timeStamp: timeStamp, content:content, documentId: documentId, userId: userId)
self.sourseArray.append(newSourse)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
}

Firestore- Showing data in Tableview

I am attempting to show my Firestore data into my Tableview but I can't seem to get it to show up.
protocol DocumentSerializeable {
init?(dictionary:[String:Any])
}
struct Sourse {
var name: String
var content: String
var timeStamp: Date
var dictionary: [String: Any] {
return [
"name": name,
"content": content,
"timestamp": timeStamp
]
}
}
extension Sourse : DocumentSerializeable {
init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let content = dictionary["content"] as? String,
let timeStamp = dictionary["timeStamp"] as? Date else {return nil}
self.init(name: name, content: content, timeStamp: timeStamp)
}
}
class SourseListTableViewController: UITableViewController {
var db: Firestore!
var sourseArray = [Sourse]()
private var document: [DocumentSnapshot] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
//initalize Database
db = Firestore.firestore()
loadData()
}
At first I tried this code below, there were no errors but nothing loaded in the tableview.
func loadData() {
db.collection("sourses").getDocuments() {
snapshot, error in
if let error = error {
print("\(error.localizedDescription)")
} else {
self.sourseArray = snapshot!.documents.flatMap({Sourse(dictionary: $0.data())})
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
After some research (reading from Firestore - Append to tableView when view is loaded ) I tried this code below, but I get the error "Cannot convert value of type '(name: String, content: String, timeStamp: Date?)' to expected argument type 'Sourse'" So I tried it with the date removed from all the code and I still couldn't get it to work.
func loadData() {
db.collection("sourses").getDocuments() {
snapshot, error in
if let error = error {
print("\(error.localizedDescription)")
} else {
for document in snapshot!.documents {
let data = document.data()
let name = data["name"] as? String ?? ""
let content = data["content"] as? String ?? ""
let timeStamp = data["timeStamp"] as? Date
let newSourse = (name:name, content:content, timeStamp: timeStamp)
self.sourseArray.append(newSourse)
}
}
}
}
Here is my numberOfRows/CellForRow to make sure its not the tableview itself. I've also double checked the "cell identifier" with my storyboard.
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return sourseArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SourseTableViewCell", for: indexPath)
let sourse = sourseArray[indexPath.row]
cell.textLabel?.text = "\(sourse.name)"
cell.detailTextLabel?.text = "\(sourse.content)"
return cell
}
You need to reload your tableView after parsing your Snapshot. It is also not a good idea to force unwrap your Snapshot:
.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let name = data["name"] as? String ?? ""
let content = data["content"] as? String ?? ""
let timeStamp = data["timeStamp"] as? Date ?? Date()
let newSourse = Sourse(name:name, content:content, timeStamp: timeStamp)
self.sourseArray.append(newSourse)
}
self.tableView.reloadData()
}
}
rbaldwin talked me through it, his answer is correct, I'm just posting the full loaddata function for the record.
func loadData() {
db.collection("sourses").getDocuments() { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let name = data["name"] as? String ?? ""
let content = data["content"] as? String ?? ""
let timeStamp = data["timeStamp"] as? Date ?? Date()
let newSourse = Sourse(name:name, content:content, timeStamp: timeStamp)
self.sourseArray.append(newSourse)
}
self.tableView.reloadData()
}
}
}
}

Updating Firestore Database causes iOS crash

When I update the firebase firestore database with any new field, it instantly kills any app running that uses the data with the fatal error in the code below.
The error I get says "fatalError: "Unable to initialize type Restaurant with dictionary [(name: "test", availability: "test", category: "test")]
I'd like to be able to update it without having the apps crash. If that happens, they have to delete and reinstall the app to get it to work again, so I think it's storing the data locally somehow, but I can't find where.
What can I do to make this reset the data or reload without crashing?
The file where the error is thrown (when loading the table data):
fileprivate func observeQuery() {
stopObserving()
guard let query = query else { return }
stopObserving()
listener = query.addSnapshotListener { [unowned self] (snapshot, error) in
guard let snapshot = snapshot else {
print("Error fetching snapshot results: \(error!)")
return
}
let models = snapshot.documents.map { (document) -> Restaurant in
if let model = Restaurant(dictionary: document.data()) {
return model
} else {
// Don't use fatalError here in a real app.
fatalError("Unable to initialize type \(Restaurant.self) with dictionary \(document.data())")
}
}
self.restaurants = models
self.documents = snapshot.documents
if self.documents.count > 0 {
self.tableView.backgroundView = nil
} else {
self.tableView.backgroundView = self.backgroundView
}
self.tableView.reloadData()
}
}
And the Restaurant.swift file:
import Foundation
struct Restaurant {
var name: String
var category: String // Could become an enum
var availability: String // from 1-3; could also be an enum
var description: String
var dictionary: [String: Any] {
return [
"name": name,
"category": category,
"availability": availability,
"description": description
]
}
}
extension Restaurant: DocumentSerializable {
//Cities is now availability
static let cities = [
"In Stock",
"Back Order",
"Out of Stock"
]
static let categories = [
"Rock", "Boulder", "Grass", "Trees", "Shrub", "Barrier"
]
init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let category = dictionary["category"] as? String,
let availability = dictionary["availability"] as? String,
let description = dictionary["description"] as? String
else { return nil }
self.init(name: name,
category: category,
availability: availability,
description: description
)
}
}
The Local Collection File with the Document.Serializable code:
import FirebaseFirestore
// A type that can be initialized from a Firestore document.
protocol DocumentSerializable {
init?(dictionary: [String: Any])
}
final class LocalCollection<T: DocumentSerializable> {
private(set) var items: [T]
private(set) var documents: [DocumentSnapshot] = []
let query: Query
private let updateHandler: ([DocumentChange]) -> ()
private var listener: ListenerRegistration? {
didSet {
oldValue?.remove()
}
}
var count: Int {
return self.items.count
}
subscript(index: Int) -> T {
return self.items[index]
}
init(query: Query, updateHandler: #escaping ([DocumentChange]) -> ()) {
self.items = []
self.query = query
self.updateHandler = updateHandler
}
func index(of document: DocumentSnapshot) -> Int? {
for i in 0 ..< documents.count {
if documents[i].documentID == document.documentID {
return i
}
}
return nil
}
func listen() {
guard listener == nil else { return }
listener = query.addSnapshotListener { [unowned self] querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshot results: \(error!)")
return
}
let models = snapshot.documents.map { (document) -> T in
if let model = T(dictionary: document.data()) {
return model
} else {
// handle error
fatalError("Unable to initialize type \(T.self) with local dictionary \(document.data())")
}
}
self.items = models
self.documents = snapshot.documents
self.updateHandler(snapshot.documentChanges)
}
}
func stopListening() {
listener = nil
}
deinit {
stopListening()
}
}
fatalError: "Unable to initialize type Restaurant with dictionary [(name: "test", availability: "test", category: "test")]
Seems pretty straightforward - that dictionary does not contain enough information to create a Restaurant object.
The error is from
if let model = Restaurant(dictionary: document.data()) {
return model
} else {
// Don't use fatalError here in a real app.
fatalError("Unable to initialize type \(Restaurant.self) with dictionary \(document.data())")
}
because your initializer returns a nil value, from:
init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let category = dictionary["category"] as? String,
let availability = dictionary["availability"] as? String,
let description = dictionary["description"] as? String
else { return nil }
self.init(name: name,
category: category,
availability: availability,
description: description
)
}
because your guard is returning nil because you do not have a description key in the dictionary.
To fix, either put a description key in the dictionary OR change your initializer to use a default description when the key is missing.
For example, here is your initializer, rewritten to use a default description, for when the description entry is missing
init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let category = dictionary["category"] as? String,
let availability = dictionary["availability"] as? String
else { return nil }
let description = dictionary["description"] as? String
let defaultDescription: String = description ?? "No Description"
self.init(name: name,
category: category,
availability: availability,
description: defaultDescription
)
}

Resources