5

I'm trying to do a simple task, to get a value from Firebase. I added the image below with the relevant screens. At least one of the print commands should print a message to the console, but it's not working. I've been trying to fix it for 1,5 days now and I still have no idea why it is not working.

Code:

import UIKit
import Firebase

class MainVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let ref = FIRDatabase.database().reference()

        ref.child("zonneschijn").observeSingleEventOfType(.Value, withBlock: { snapshot in
            if snapshot.value is NSNull {
                print("Does not exist currently")
            } else {
                print("Exists currently")
            }

        })
    }
}

I've also tried to use viewDidAppear, also with no succes.

Image with the relevant screens

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

6

If you are not authenticating your user's.

Go to Rules tab in Realtime Database in Firebase console.

Default Security rules of firebase are something like this :-

{
 "rules": {
    ".read": "auth != null",
    ".write": "auth != null"

   }
}

Which means only authenticated users(Those user's who have been signed in either with gmail, Facebook, gitter, email..etc) can read or write data... Clearly you are not authenticating your user that's why you can not retrieve any data with these default Security Rules .

This is a good practice to only allow authenticated users to have access to the DB, as it is more secure.If you want to read data anyways , Modify your security rules to this:-

Warning :- Not Recommended if you are making app that has some private DB.

   // These rules give anyone, even people who are not users of your app,
    // read and write access to your database

    {
      "rules": {
        ".read": true,
        ".write": true
      }
    }

A better alternative :-

Do read : Security Rule's

Dravidian
  • 9,945
  • 3
  • 34
  • 74
  • Hm it's still not printing, I applied the Not Recommended code. Also, I'm not using user accounts since it is just a simple task meant for the main screen. It wouldn't make sense to login especially for that. – Fabian Bouwmeester Sep 09 '16 at 13:57
  • 1
    Updated my answer, also try looking :- https://firebase.google.com/docs/database/security/quickstart – Dravidian Sep 09 '16 at 14:00
  • The 'true' part makes it work. So it works, finally! Good to know from now on. Thanks for your time Dravidian. Means a lot. – Fabian Bouwmeester Sep 09 '16 at 14:03
  • Hi, can we get an updated version of this answer. The code doesn't work anymore – Tyler Rutt Sep 25 '19 at 21:29