Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase,Swift : Not able to retrieve Data

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

like image 509
Fabian Bouwmeester Avatar asked Sep 09 '16 11:09

Fabian Bouwmeester


1 Answers

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 :-

  • Sign in your user(start with email-password : Firebase EMAIL- Password Auth)
  • Then access your DB

Do read : Security Rule's

like image 188
Dravidian Avatar answered Sep 27 '22 17:09

Dravidian