Read data from Firebase to swift3 EXC_BAD_INSTRUCTION - swift

I have the following firebase database
This is how I add data into the database
And this is how I try to get the data out of Database but I get this error EXC_BAD_INSTRUCTION

Your force unwrap is saying that the dictionary should only consist of String: String. But as you can see, the value for the key value is an integer, which will be parsed as an NSNumber according to the Firebase documentation so String: AnyObject is what you want to unwrap as.
let snapshotValue = snapshot.value as Dictionary<String, AnyObject>
A little bit of safer code would be:
guard let snapshotValue = snapshot.value as? Dictionary<String, AnyObject>
else {
return
}

The error appears because my database value is Integer and I want to read it as String.

Related

How to unpack multiple levels of nested JSON in Firebase Database

In my app, I would regularly have a JSON topic, for example message, then nested in that is a random ID, then the message text as a string inside the random ID. But, I need to decipher multiple levels of random IDs. Is that possible in Firebase for Swift? This is what I mean:
This is my code:
Database.database().reference().child("app").observe(.childAdded) { (snapshot) in
//app is first in the JSON tree
let dict = snapshot.value as! [String: Any]
let msg = dict["message"] as! String
Obviously this is crashing the app, as it's looking for "Message" in the first RandomID. Is there a solution to this? I haven't found resources for specifically what I'm looking for. Thank you.
You'll want to loop over the children of snapshot as shown here:
Database.database().reference().child("app").observe(.childAdded) { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot //downcast
let dict = snap.value as! [String: Any]
let msg = dict["message"] as! String
}
})
Also see:
Get data out of array of Firebase snapshots
Swift Firebase -How to get all the k/v when using queryOrdered(byChild: ).queryEqual(toValue: )
other questions about looping over child nodes

swift3 How to remove Optional [duplicate]

This question already has answers here:
Printing optional variable
(15 answers)
Cannot get rid of Optional() string
(5 answers)
Closed 5 years ago.
this is my code:
func uplouadPost() {
// shortcut to data to be php
let parseJSON = UserDefaults.standard.value(forKey: "parseJSON") as?
NSDictionary
let userID = parseJSON!["userID"] as! String
....
if error == nil {
do {
// json containes $returnArray from php
let json = try JSONSerialization.jsonObject(with: data!,
options: .mutableContainers) as? NSDictionary
print("========================\(userID)")
print I get ========================Optional(23)
But I don't want Optioanl
how to just get 23
What's more, I tried to unwrap the "userID" by this way. However it doesn't work
let unwrappedUserID = [userID]
print (unwrappedUserID)
Thank you guys
The best method of checking for and unwrapping Optionals is using either a guard statement or if-let statements.
So suppose you have a dictionary defined as:
let parseJson: [String: Any]? = ["userId": 23]
Even though it has a value, it is still an Optional type so to access the values in the dictionary we want, we need to check for the possibility of it having a nil value, assuming we didn't create it and know that it has a real value.
Using if-let statements, we can do:
if let json = parseJson {
// WILL ONLY EXECUTE IF parseJson IS NOT nil
// json is now of type [String: Any] instead of [String: Any]?
let userId = json["userId"]
print("=========\(userId)") // =========23
}
This creates a new scope where the json constant now contains the non-nil and unwrapped optional value of parseJson. In that case if parseJson did equal nil, then the code inside of the if-let block would not execute.
The other option is a guard statement, which is very similar.
guard let json = parseJson else {
// ONLY EXECUTES IF parseJson IS nil
// MUST EXIT CURRENT SCOPE AS A RESULT
return // or throw NSError()
}
let userId = json["userId"]
print("==========\(userId)") // ==========23
In this case, the code after the guard will only execute if parseJson is non-nil because the inside of the guard block must exit the scope.
Try this, let unwrappedUserID = userID!

Firebase Swift: Converting Snapshots to Dictionary

I have the following snapshots and I'm trying to create an array of dictionary. I have been fiddling ways to cast as [String: Bool] or getting snapshot.value or whatsoever but can't seem to work correctly. Any advice how can I go about doing it?
ref.child("activities").child(userUID!).observe(.childAdded, with: { (snapshot) in
print(snapshot)
}) { (error) in
print(error.localizedDescription)
}
The snapshots looks like this:
Snap (Person1) 0
Snap (Person2) 0
Snap (Person3) 0
I am trying to write an array like this:
Optional(["Person3": false, "Person2": false, "Person1": false])
Some advice is much appreciated, thanks!
You need to cast the snapshots value as [String:Bool]. You can do it with the code below.
snapshot.value as? [String:Bool]
Edit:
You say it doesn't work...are you sure that you have any data to retrieve?
If you do like this you'll find out if you have any data.
if let value = snapshot.value{
//there is data available
let data = value as [string:Any]
print("\(data)")
}else{
//there is no data available. snapshot.value is nil
print("No data available from snapshot.value!!!!")
}

Error of "Ambiguous use of 'subscript'" shown after upgraded Xcode

After I upgrade my Xcode to the latest version. It shows this error. Not sure what it means.
The ambiguous error occurs when the type of the object is AnyObject and the compiler has no idea whether the object can be key subscripted.
The solution is to cast result down to something suitable.
It seems to be a dictionary
if let dict = result as? [String:AnyObject] {
let userId = dict["id"] as! String
...
}
You have to define the result type, for example if this is a Dictionary try:
let dic: NSDictionary = result
let userId: String = dic["id"] as! String

Convert String to NSDictionary by ignoring string literal

I'm getting dictionary value from server in form of String. Now when I try to use that String, it contains \ before ".
I get below value from my web service:
“\”{\\\”111\\\”:\\\”abc\\\”, \\\”222\\\”:\\\”xyz\\\”}\”
I'm trying to convert this string to NSDictionary. Can you please some one guide me for this. Which is the easiest way to convert this to NSDictionary. My current code is as below, but it's not working
var permValue = perm.value?.stringByReplacingOccurrencesOfString("\\", withString: "")
let data = permValue?.dataUsingEncoding(NSUTF8StringEncoding)
if let dict = try! NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary{
print("Permission Dictionary : \(dict)")
}
I'm getting an error while converting data to NSDictionary.
Please help. Any help will be appreciated