Maarten Weyns Maarten Weyns - 9 months ago 33
iOS Question

FirebaseDatabase web iOS / OSX

I'm working on a website for a school project containing a button which you need to press. When pressed, the button takes a value from the database, child 'aantal' and adds 1. When that is done, it re-uploads it back to the database. One page further, you can see the live number of that child. The problem is, this is not working on iOS 9 or lower and on OSX Yosemite or lower. On android and windows it works fine.

Reusable code;

This is just a button. If you press the button it adds 1 on the int. This is very strange because it doesn't doesn't work on the OS mentioned above.

<script src="https://www.gstatic.com/firebasejs/3.6.9/firebase.js"></script>
<script language="JavaScript">
// Initialize Firebase
var config = {
apiKey: //API KEY,
authDomain: //FIRBASE DOMAIN,
databaseURL: //DATABASE URL,
storageBucket: //STORAGE BUCKET,
messagingSenderId: //MESGSENDID
};
firebase.initializeApp(config);
var number;
var database = firebase.database().ref().child('aantal');
function buy() {
database.on('value', snap => number = snap.val());
var count = parseInt(number, 10) + 1;
database.set(count);
}
</script>


This code will not work, initialise own Firebase project for testing.
For security reasons I removed my details.

Answer Source

Edit Turns out Safari (9.1/iOS 9.3 and below) doesn't support arrow functions.

Changing database.on('value', snap => number = snap.val()); to database.on('value', function(snap) { number = snap.val()}); fixed the issue.

Well I mean, that code shouldn't work anywhere.

function buy() {
    database.on('value', snap => number = snap.val());
    var count = parseInt(number, 10) + 1;
    database.set(count);
}

Firebase is asynchronous, and you're not waiting for it to actually load number from the database.

This should work.

function buy() {
    database.on('value', snap => {
      number = snap.val();
      var count = parseInt(number, 10) + 1;
      database.set(count);
    });
}

I don't know whether this is actually the issue you're having or if you just wrote this in your example. Also, when incrementing values you should be using Transactions.

function buy() {
    database.transaction(function(value) {
        if (value) {
            value++;
        }
        return value;
    });
}