Using iOS + Swift, what's the best method to allow special characters .$#[]/ in my Firebase database keys (node names)?
-
Possible duplicate of [Adding Firebase data, dots and forward slashes](https://stackoverflow.com/questions/19132867/adding-firebase-data-dots-and-forward-slashes) – AL. Jun 01 '17 at 02:31
-
1Hi Trev14. I see you've also added an answer in the possible duplicate post (which is great!), but if the context of the question is similar, I think posting another question (with just different tags) and adding the same answer isn't good. Nonetheless, thanks for contributing to the community. Cheers! – AL. Jun 01 '17 at 02:33
-
Why can't you use those characters in a Firebase database string? ".$#[]/" is perfectly a valid *value* in Firebase. – Jay Jun 01 '17 at 17:58
2 Answers
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)
}
}

- 3,626
- 2
- 31
- 40
-
1This is a very interesting approach but the initial question should probably be more specific (see my answer) as you are asking about using Special Characters in Firebase *Keys* not *Strings* - we don't want to mislead future readers who may be inexperienced with Firebase. I gave you a up arrow for creative thinking. – Jay Jun 01 '17 at 18:25
-
Ah thank you @Jay. From my experiences so far the app crashed every time I tried to save something with those characters...obviously because I was creating a key from them as well as putting them inside values. – Trev14 Jun 02 '17 at 00:31
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.

- 34,438
- 18
- 52
- 81