Elfuthark
Elfuthark

Reputation: 261

Data from iOS app not saving to Firebase Database

I'm looking to save data that has been stored in 4 labels and 1 text view in my app onto my Firebase Database but I am not having any success, below is the code I have written. The app is a form that gets filled in and has a save button that once pressed should send the data to my firebase database but when I check there is nothing there?

I'm not even sure how I would check for errors in the console for this problem.

import UIKit
import CoreLocation
import Firebase

class AddSightingViewController: UIViewController {

    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UITextView!

    var locManager = CLLocationManager()
    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set Date & Time

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium

        dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d, yyyy") // // set template after setting locale

        let dateString = "\(dateFormatter.string(from: Date() as Date))"
        dateLabel.text = String(dateString)

        let timeFormatter = DateFormatter()
        timeFormatter.timeStyle = .medium

        timeFormatter.setLocalizedDateFormatFromTemplate("hhmm")

        let timeString = "\(timeFormatter.string(from: Date() as Date))"

        timeLabel.text = String(timeString)

        // Set Latitude & Longitude

        locManager.requestWhenInUseAuthorization()

        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
            currentLocation = locManager.location
            self.latitudeLabel.text = String("\(currentLocation.coordinate.latitude)")
            self.longitudeLabel.text = String("\(currentLocation.coordinate.longitude)")
        }
    }

    func post() {

        let date = dateLabel.text
        let time = timeLabel.text
        let latitude = latitudeLabel.text
        let longitude = longitudeLabel.text
        let sightingDescription = descriptionLabel.text

        let post: [String : AnyObject] = ["date" : date as AnyObject,
                                          "time" : time as AnyObject,
                                          "latitude" : latitude as AnyObject,
                                          "longitude" : longitude as AnyObject,
                                          "Description" : sightingDescription as AnyObject]

        var ref: DatabaseReference!

        ref = Database.database().reference()


        ref.child("Sightings").childByAutoId().setValue(post)

    }

    @IBAction func saveButton(_ sender: Any) {

        post()

    }
}

Upvotes: 1

Views: 2109

Answers (1)

jlmurph
jlmurph

Reputation: 1090

Do you get any erroneous messages on console when you initialize Firebase, in AppDelegate, or when you actually do post? If you do, update your post

If not: make sure Allows Arbitrary Loads is set to true on your info.plist.

Make sure the write permissions are appropriate:

By default Firebase implements users of apps to be authenticated with firebase through one of the Auth methods provided by the service. Sometimes this is overlooked when creating new projects. If you dont want authentification (not recommended, but can be a solution for publicly accessible databases), you just need to go to Database (in your project) > Rules and change it to this:

// 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
  }
}

You can check out how to play around with the basic-level rules here.

Otherwise if these dont fix it, provide more code or the console logs on app launch and when you post! (Also make sure the IBAction does actually fire.. you'd be surprised) Usually, you should get console messages on App Launch by default if firebase is being initialized. Otherwise, you wont get XCode console logs when you do post with the setValue method you're using. It's usually better to use the setValue(_ value: Any?, withCompletionBlock block: @escaping (Error?, FIRDatabaseReference) -> Void) method like so:

    let ref = Database.database().reference().[..all the childs until where you post]

    ref.setValue(item) { (err, resp) in
                guard err == nil else {
                    print("Posting failed : ")
                    print(err)

                    return
                }
                print("No errors while posting, :")
                print(resp)
            }

From here, post the err, and resp content when you do if none of the previous suggestions work!

Upvotes: 3

Related Questions