breno morais
breno morais

Reputation: 85

Crash when I try to insert Date as Key on Firebase database

I am configuring my database according to my documentation. I did all the initial configuration: I will put the code below

AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()

        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self
        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

        if (Auth.auth().currentUser) != nil {
            presentHome()
        } else {
            presentSignIn()
        }

        return true
    }

The problem is that when I create the database reference and having insert something I get this error:

terminating with uncaught exception of type NSException

ViewController:

var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        ref = Database.database().reference()
    }

@IBAction func saveTask(_ sender: Any) {
        let task:[String:Any] = [
            "title":self.titleTxtField.text!,
            "type":type!,
            "observations":"Teste de tarefa",
            "finished":false,
            "images":[
                "image1":"https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg",
                "image2":"http://www.planwallpaper.com/images#static/images/beautiful-sunset-images-196063.jpg"
                ]
        ]

        let date = Date().timeIntervalSince1970
        ref.child("\(self.user!.uid)/tasks/\(date)").setValue(["teste":"teste"])
    }

Upvotes: 0

Views: 199

Answers (1)

Giuseppe Sapienza
Giuseppe Sapienza

Reputation: 4708

I think your problem is on this line:

let date = Date().timeIntervalSince1970

This print some characters which are not allowed to be entered as child key on Firebase

So, if you want a structure like this:

root
--- year
------ month
--------- day

Try to do this:

  1. Extract the DateComponents from the Date

  2. Create a new String with the results

And add the new string as child with this code:

let components = Calendar.current.dateComponents([.day, .month, .year], from: yourDate)
let ref = Database.database().reference()
ref.child("root/\(components.year!)/\(components.month!)/\(components.day!)")

Upvotes: 1

Related Questions