'failed: permission_denied when setValue: or removeValue: in Firebase Database | Swift 4

I have seen lots of answers in stackoverflow but none is working for me!

This is my code:

import UIKit
import Firebase
class ViewController: UIViewController {

    @IBOutlet var txt: UITextField!
    var ref = DatabaseReference.init()
    override func viewDidLoad() {
        super.viewDidLoad()
        loginAnony()
        self.ref = Database.database().reference()
    }

    func loginAnony(){
        Auth.auth().signInAnonymously(){
            (user,error) in
            if let error = error{
                print(error.localizedDescription)
            }else{
                print("User ID\(user?.user.uid)")
            }
        }
    }

    @IBAction func btnClick(_ sender: Any) {
        self.ref.child("chat").setValue("Yogesh")
    }

}

My database rule:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

I have remove with this:

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

But it's still not working. Can anyone help me with this?



Solution 1:[1]

Firebase needs to be configured in your AppDelegate like this

func application(_ application: UIApplication, didFinishLaunchingWithOptions... {
        FirebaseApp.configure()

Then in your viewController set up a class var:

class ViewController: UIViewController{
    var ref: DatabaseReference!

so, don't do this: var ref = DatabaseReference.init()

Then in a viewDidLoad, initialize the class var and then authenticate

override func viewDidLoad() {
   super.viewDidLoad()
   self.ref = Database.database().reference()
   //proceed to authenticate

Also, Firestore rules do NOT apply to the Firebase Realtime Database, it has its own set of rules.

service cloud.firestore //doesn't do anything to RTDB

So leave your Firebase database rules as the default of

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

Solution 2:[2]

Opening permissions creates a security hole , the most logical way is to log into the application.

Read the Firebase docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 yhackup