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

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)
}
}

Related

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
}
}

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.

Catching RealmSwift write errors i.e. delete

How exactly do I catch RealmSwift add/delete errors?
i.e.
do {
try realm.write {
realm.delete(MyRealmObject())
}
completion(true)
} catch {
completion(false)
}
In this example I've deliberately tried deleting a RealmObject that I've just made up (to make it fail), but it doesn't catch, instead I get this error:
Terminating app due to uncaught exception 'RLMException', reason: 'Can only delete an object from the Realm it belongs to.'
I haven't seen any examples of people handling specific delete/add errors - is there a reason for this?
Not sure if this is what you're looking for but the following code catches and identifies specific add errors. However, errors accessing different instances of realm are handled differently. So starting with this...
class MyObject: Object {
#objc dynamic msg = ""
}
do {
let realm = try Realm()
let a0 = MyObject()
a0.msg = "Hello, World"
try! realm.write {
realm.add(a0)
}
} catch let error as NSError {
print(error.localizedDescription)
}
to then expand.... do the following to ensure the object being deleted matches the realm you are deleting it from.
do {
let realm = try Realm()
if a0.realm == realm {
try! realm.write {
realm.delete(a0)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
Realm developers extend NSError class with their custom description Can only delete an object from the Realm it belongs to and do FatalError in the predefined list of errors they expect ( may be for a good use of the their library as a help to the developer to correctly use it ) , so they intentionally don't throw an exception that the try can catch

Ignore records in FirebaseDB with 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})

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.