Ad

Updating Collection In Firebase Returns Error "found Nil While Unwrapping Optional Value"?

I'm making this app where the idea is that you create a profile, add your dogs, and then update a timer on them (when they last ate, took a walk, etc). I'm having some issues with Firebase though. I managed to have the user add dogs to their account, but now that I'm trying to update some values on a certain dog the app crashes with a "Unexpectedly found nil while unwrapping an Optional value" which seems to be due to Firebase. My Database contains the user, their dogs and a collection of the dogs values, such as firstTimer. When I try to update this value with the setData() method it just keeps crashing and nothing shows in my database. i've also tried to update values individually but to no avail. Please tell me if I'm going about this the wrong way and if there's some other approach to try, thanks!

import Foundation
import Firebase
import UIKit

//DogViewController
class MyDogViewController: UIViewController {

    var db: Firestore!
    var auth: Auth!
    var storage: Storage!
    var thisDog: DogEntry?
    var dogRef: DocumentReference!     

    override func viewDidLoad() {
        thisDog?.firstTimer = (formattedDate)

            if let dog = thisDog?.toAny() {
                print("Let")
                //THE PROGRAM PRINTS LET
                dogRef.setData(dog)
                //BUT CRASHES HERE
            }
            else {
                print("Error")
            }
        }
    }
}

//Dog Modal Class
class DogEntry {

    var name: String
    var image: String
    var firstTimer: String
    var secondTimer: String
    var walking: Bool = false
    var walkArray: [String]
    var id: String = ""


    init(name: String, image: String, firstTimer: String, secondTimer: String, walking: Bool, walkArray: [String]) {
        self.name = name
        self.image = image
        self.firstTimer = firstTimer
        self.secondTimer = secondTimer
        self.walking = walking
        self.walkArray = walkArray
   }

    init(snapshot: QueryDocumentSnapshot) {
        let snapshotValue = snapshot.data() as [String : Any]
        name = snapshotValue["name"] as! String
        image = snapshotValue["image"] as! String
        firstTimer = snapshotValue["firstTimer"] as! String
        secondTimer = snapshotValue["secondTimer"] as! String
        walking = snapshotValue["walking"] as! Bool
        walkArray = snapshotValue["walkArray"] as! [String]
        id = snapshot.documentID
    }

    func toAny() -> [String: Any] {
        return ["name": name, "image": image, "firstTimer": firstTimer, "secondTimer": secondTimer, "walking": walking, "walkArray": walkArray]
    }
}
Ad

Answer

Your dogRef is an implicitly unwrapped optional. You need to give it a value before you call it.

Ad
source: stackoverflow.com
Ad