Ignore records in FirebaseDB with swift - swift

Im working on a swift app that displays records from firebase to a table view controller.
I have successfully been pulling in all data, But I have since added another field to the DB called "secretKey".. This doesn't not need to be used on the table view as its used elsewhere in the app
But now each time I try to run the app I get the following errors
2018-05-07 12:24:24.616490+0100 Loop Guardian[21847:9857567] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSTaggedPointerString 0xa030818c015ea1f9> valueForUndefinedKey:]: this class is not key value coding-compliant for the key createdAt.'
*** First throw call stack:
(0x18204b164 0x181294528 0x18204ae2c 0x1829fe434 0x182944e20 0x182944874 0x18297d930 0x1030084b0 0x103008740 0x1030f2840 0x1044892cc 0x10448928c 0x10448dea0 0x181ff3344 0x181ff0f20 0x181f10c58 0x183dbcf84 0x18b6695c4 0x10301de44 0x181a3056c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
This only happens when the secretKey is present in the DB.. If I remove it the app works fine.
I somehow need to ignore this field
Heres the code used to pull the records from the DB
func observeMessages() {
let key = UserDefaults.standard.value(forKey: "uid") as! String
DBrefs.databaseMessages.child(key).observe(.value, with: { (snapshot) in
if snapshot.exists() {
let messageData = snapshot.value as! Dictionary<String, AnyObject>
self.dataArr = []
for (key,data) in messageData {
self.dataArr.append(data)
}
//THIS IS WHERE THE ERROR IS THROWN.. THREAD 1: SIGNAL SIGABRT
self.dataArr = (self.dataArr as NSArray).sortedArray(using: [NSSortDescriptor(key: "createdAt", ascending: true)]) as [AnyObject]
self.tblMessage.reloadData()
}
else {
}
})
}
Any help is appreciated
Thanks
Oliver

for (key,data) in messageData {
if (key == "secreyKey") {
continue;
}
self.dataArr.append(data)
}
Also use Swift method to sort the Array. Don't use NSArray use Array instead.
Like below code:
self.dataArr.sorted(by: {$0["createdAt"] as? Int64 ?? 0 < $1["createdAt"] as? Int64 ?? 0})

Related

swift 'Terminating app due to uncaught exception 'RLMException' Error

I am trying to add new data to realm
The following error occurs when trying to
realm.add(addData)
'Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to create an object of type 'CalDBRealm' with an existing primary key value '2'.''
I tried with realm.create(CalDBRealm.self, value:addData, update: .modified) but no error
But this is not what I want. I want to add data, not update data.
What should I do?
Thank you
let realm = try! Realm()
let data = realm.objects(CalDBRealm.self).filter("date == %# AND listId == %#", todayDate, listId)
print("data type = \(data.count)")
if data.count > 0 {
time = data.first!.time
}
else
{
try! realm.write {
let addData = CalDBRealm("", todayDate, 0, "", listId)
//realm.add(addData)
realm.create(CalDBRealm.self, value:addData, update: .modified)
}
}

Swift 5 Firestore: Checking if collection exists in database

I'm trying to check if a certain collection exists in my Firestore database, and here is my code for doing so:
let db = Firestore.firestore()
db.collection(pickedClass).getDocuments { (snapshot, error) in
if error == nil && snapshot != nil {
if snapshot!.documents.count > 0 {
for document in snapshot!.documents {
let documentData = document.data()
let info = documentData["info"] as! [String: Any]
output.append(object)
}
self.performSegue(withIdentifier: "showTutors", sender: output)
} else {
self.createAlert(title: "No Tutors Found", message: "Sorry, there are no tutors for this class", buttonMsg: "Okay")
}
}
}
The exception I get from running this apparently comes from the second line db.collection(pickedClass).getDocuments, and is as follows:
*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid collection reference. Collection references must have an odd number of segments, but has 0'
terminating with uncaught exception of type NSException
The bizarre thing is that most times this isn't an issue and the user sees the alert when the collection doesn't exist, but sometimes this happens. I never faced this issue until today, and I've been running this database and this snippet of code for over 2 months now.
Would really appreciate any help!
Hi, I'm implementing FireStore in first time as I study I found this
answer you can use this below mentioned code.
Firestore.firestore().collection("YOUR_COLLECTION_NAME_HERE")
.document("INSIDE_YOUR_COLLECTION_USE_DOCUMENT_ID_HERE_WHICH_YOU_WANT_TO_CHECK")
.getDocument { (document, error) in
debugPrint(document?.exists)
if document?.exists ?? false {
// EXIST
} else {
// NOT-EXIST
}
}

saving data array causes crash swift

I tried adding an item to an arrar and saving in Userdefault but the app crashed and I would love anyone to point me to what I am doing wrong
private func putArray(_ value: GMSAutocompletePrediction?, forKey key: String) {
guard let value = value else {
return
}
log("THE MESSAGE \(value)", .fuck)
var newArray = getArray(forKey: key)
log("THE MESSAGE ARRAY \(newArray)", .fuck)
if newArray.contains(value) {
newArray.remove(at: newArray.firstIndex(of: value)!)
} else {
newArray.append(value)
}
storage.setValue(NSKeyedArchiver.archivedData(withRootObject: newArray), forKey: key)
}
error from crash
[GMSAutocompletePrediction encodeWithCoder:]: unrecognized selector sent to instance 0x2818f9ce0
2019-09-26 13:40:07.300856+0100 MAX.NG Staging Debug[4440:1410011] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GMSAutocompletePrediction encodeWithCoder:]: unrecognized selector sent to instance 0x2818f9ce0'
GMSAutocompletePrediction doesn't conform to NSCoding so you can't save it to user defaults , you may extract important details from it and make a custom model to save

Terminating app due to uncaught exception 'NSUnknownKeyException' when updating Firebase

When creating a function to add a key-value pair in Firebase I get a crash with the following report
* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key score.'
* First throw call stack:
(0x1dbd9a3a8 0x1daf9fd00 0x1dbcb36c8 0x1dc796054 0x1dc7ed2a0 0x1dc7070e0 0x102e58cc8 0x102e50640 0x102e4ed18 0x102e4f2c8 0x103f24214 0x103f13f84 0x1daf9b760 0x20906dbf0 0x208af1f94 0x208af22c8 0x208af12dc 0x2090a6a90 0x2090a7cc8 0x209086f50 0x209152150 0x20915490c 0x209154c7c 0x20914d9c4 0x1dbd2a444 0x1dbd2a3c0 0x1dbd29c7c 0x1dbd24950 0x1dbd24254 0x1ddf63d8c 0x20906c4c0 0x102f2befc 0x1db7e0fd8)
libc++abi.dylib: terminating with uncaught exception of type NSException
Message from debugger: failed to send the k packet
The layout of my database is as such:
I believe the problem is I'm calling it to the wrong path in my function.
My functions to update the "score" is :
func updateRecentScore(chatRoomId: String, score: Int) {
let date = dateFormatter().string(from: Date())
firebase.child(kRECENT).queryOrdered(byChild: kCHATROOMID).queryEqual(toValue: chatRoomId).observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for recent in ((snapshot.value as! NSDictionary).allValues as Array) {
updateRecentScoreItem(recent: recent as! NSDictionary, score: score)
}
}
}
}
func updateRecentScoreItem(recent: NSDictionary, score: Int) {
var score = recent[kSCORE] as! Int
let values = [kSCORE: score] as [String: Any]
firebase.child(kRECENT).child((recent[kRECENTID] as? String)!).updateChildValues(values as [NSObject : AnyObject]) {
(error, ref) -> Void in
if error != nil {
ProgressHUD.showError("Couldnt update recent: \(error!.localizedDescription)")
}
}
}
I call the function to update it here:
let score = recentsRef.child(kRECENTID).value(forKey: kSCORE) as? Int
let newScore = score! + 1
let score1 = firebase.child(kRECENT).queryOrdered(byChild: kCHATROOMID).queryEqual(toValue: chatRoomId).value(forKey: kSCORE) as? Int
let newScore1 = score1! + 1
updateRecentScore(chatRoomId: chatRoomId, score: newScore1)
All help is appreciated as I'm not sure what to do to fix this and I have tried to look everywhere for an answer. If you need any further information please ask.
I think you're looking for this:
func updateRecentScore(chatRoomId: String, score: Int) {
let date = dateFormatter().string(from: Date())
firebase.child(kRECENT).queryOrdered(byChild: kCHATROOMID).queryEqual(toValue: chatRoomId).observeSingleEvent(of: .value) { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for child in snapshots {
child.ref.child(kSCORE).setValue(score+1)
}
}
}
}
The main differences:
I loop over the child nodes with the built-in children property, which means I get a Snapshot, which allows me to simply look up the ref of each child.
I call setValue() directly on the score property, since you're only updating that property. Using updateChildValues is really only useful if you want to update multiple-but-not-all properties in one go.

Exception throw for null data with optional Int type in Realm

I am taking my first foray into using Realm (0.98.1 via Cocoapods, Xcode 7.2) and am running into a small problem that I am not sure how to solve.
I have a model class called Airport that declares a property
let elevationFt = RealmOptional<Int>()
I am creating a set of Airport objects and persisting them in the following way
public func cacheDataToPersistanceStore(data:NSArray) -> Bool {
var success = true
autoreleasepool {
do {
let realm = try Realm()
realm.beginWrite()
for object in data {
guard let dictionaryValues = object as? Dictionary<String, AnyObject> else {
debugPrint("Unable to convert data to correct type")
success = false
return
}
if(dictionaryValues["airportID"] as! Int == 6605) {
realm.create(Airport.self, value: dictionaryValues, update: true)
}
}
try realm.commitWrite()
}
catch(let e) {
debugPrint(e)
success = false
}
}
return success
}
For the airport entry in question, the dictionary that stores the relevant data looks to have a null value for the key "elevationFt", so I assume things will be OK for the optional Int property
Here is a string version of the dictionary:
["gps_code": 01MD, "ident": 01MD, "iata_code": , "local_code": 01MD, "keywords": , "elevationFt": , "type": seaplane_base, "municipality": Annapolis, "iso_country": US, "airportID": 6605, "longitudeDeg": -76.45600128173828, "latitudeDeg": 38.99919891357422, "iso_region": US-MD, "wikipedia_link": , "name": Annapolis Seaplane Base, "scheduled_service": no, "continent": NA, "home_link": ]
However once the create function starts for this set of data, an exception is thrown:
Terminating app due to uncaught exception 'RLMException', reason: 'Invalid value '' for property 'elevationFt''
I am guessing I have something set up incorrectly, but I am not quite sure how to fix this other than to clean my source data for that particular field.
The screenshot from the debugger shows that elevationFt is an empty string, which is not a number or null, so it is not a valid value for an optional int property.