Reputation: 4116
Using iOS + Swift, what's the best method to allow special characters .$#[]/ in my Firebase database keys (node names)?
Upvotes: 0
Views: 1726
Reputation: 35659
The question is
How Do I Allow Special Characters in My Firebase Realtime Database?
The actual answer is there is nothing required to allow Special Characters in Firebase Realtime Database.
For example: given the following code
//self.ref is a reference to the Firebase Database
let str = "this.is/a#crazy[string]right$here.$[]#/"
let ref = self.ref.childByAutoId()
ref.setValue(str)
When the code is run, the following is written to firebase
{
"-KlZovTc2uhQXNzDodW_" : "this.is/a#crazy[string]right$here.$[]#/"
}
As you can see the string is identical to the given string, including the special characters.
It's important to note the question asks about allowing special characters in strings. Everything in Firebase is stored as key: value pairs and the Values can be strings so that's what this answer addresses.
Key's are different
If you create your own keys, they must be UTF-8 encoded, can be a maximum of 768 bytes, and cannot contain ., $, #, [, ], /, or ASCII control characters 0-31 or 127.
The bigger question goes back to; a structure that would require those characters to be included as a key could (and should) probably be re-thought at as there are generally better solutions.
Upvotes: 0
Reputation: 4116
Add percent encoding & decoding! Remember to allow alphanumeric characters (see example below).
var str = "this.is/a#crazy[string]right$here.$[]#/"
if let strEncoded = str.addingPercentEncoding(withAllowedCharacters: .alphanumerics) {
print(strEncoded)
if let strDecoded = strEncoded.removingPercentEncoding {
print(strDecoded)
}
}
Upvotes: 2