0

I think I have a strange one here.... I am getting an

fatal error: unexpectedly found nil while unwrapping an Optional value

when I am trying to get data from my Firebase database for my tableview. I used the code in another part of my app and it works great, so not sure why it is not working here...

I have built a data model:

import Foundation
import Firebase
import FirebaseDatabase

class Modules {

    private var _originalModules: String!
    private var _imageUrl: String!
    private var _postKey: String!
    private var _postRef: FIRDatabaseReference!


    var originalModules: String {
        return _originalModules
    }

    var imageUrl: String {
        return _imageUrl
    }

    var postKey: String {
        return _postKey
    }

    init(originalModules: String, imageUrl: String) {
        self._originalModules = originalModules
    //    self._imageUrl = caption
    }

    init(postKey: String, postData: Dictionary<String, AnyObject>) {
        self._postKey = postKey

        if let originalModules = postData["originalModules"] as? String {
            self._originalModules = originalModules

        }

        if let imageUrl = postData["imageUrl"] as? String {
            self._imageUrl = imageUrl


        _postRef = DataService.ds.REF_MODULE.child(_postKey)

        }
    }
}

I presume that I am connected to the database as I can print the correct data into the consul using this code:

DataService.ds.REF_MODULE.queryOrdered(byChild: "originalModules").observe(.value, with: { (snapshot) in

       self.modulesArray = []
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                    for snap in snapshot {
                        print("SNAP: \(snap)")

then when I try to put this data into the array with the code below I cannot print into the consul and I receive the error mentioned above.

if let postDict = snap.value as? Dictionary<String, AnyObject>{
                        let key = snap.key as String
                        let post = Modules(postKey: key, postData: postDict)
                        self.modulesArray.insert(post, at: 0)
                        //self.modulesArray.append(post)
                        print ("This is the array from Firebase: \(self.modulesArray)")

The error also highlights the line with return _originalModules in the data model, so I presume that the array is empty because I have not properly linked the data call and the array somehow

Any and all help is greatly appreciated! Let me know if you require any clarification in order to provide me with solutions.

UPDATE! Database Structure

{
  "Module" : {
    "originalModules" : {
      "CreatingResults" : "Creating Results",
      "EffectiveCommunication" : "Effective Communication",
      "PresentationSkills" : "Presentation Skills",
      "ProblemSolving" : "Problem Solving",
      "SelfAwareness" : "Self Awareness",
      "Teamwork" : "Teamwork"
    }
  },
   "posts" : {
    "-KcTZfFT58IPT5ZJJRPX" : {
      "caption" : "hello?",
      "imageUrl" : "https://firebasestorage.googleapis.com",
      "likes" : 1
    },
    "-KcTZodrcehJ-VmSU0Lh" : {
      "caption" : "Erin is a nerd",
      "imageUrl" : "https://firebasestorage.googleapis.com",
      "likes" : 1
    },
}

and for what it is worth - the tableview code...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

      let post = modulesArray[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) as! PerfectPracticeTableViewCell

        cell.configureCell(post: post)

        return cell
    }

and the configureCell code:

class PerfectPracticeTableViewCell: UITableViewCell {


    @IBOutlet weak var ppTableLabel: UILabel!
    @IBOutlet weak var ppTableImage: UIImageView!
    @IBOutlet weak var backgroundCardView: UIView!

    var modulesArray: Modules!



    func configureCell(post: Modules) {
        self.modulesArray = post
        self.ppTableLabel?.text = post.originalModules
      //  cell.ppTableImage?.image = image[(indexPath as NSIndexPath).row]
    }
theGuiza
  • 11
  • 5
  • @Nazmul thanks for the suggested post. I have looked at that post and checked the errors and the ibOutets etc. I think the problem is with my code not actually pulling the data into the array... – theGuiza Mar 30 '17 at 20:03
  • I copy and pasted (most) of your code into a project and it ran fine. The only changes I made were removing the imageUrl code in the Modules class and also moved the *print("This is the array* code to after the for loop. The problem is one of the nodes in Firebase is either missing a *originalModules* key or perhaps it's misspelled/capitalize. If I add a node in Firebase that doesn't have the correct children keys, I get the same error message. I vote to reopen as it's not a duplicate question as the OP appears to understand optionals. – Jay Mar 30 '17 at 22:04
  • Thanks @Jay.. this is driving me a little crazy! my firebase database is set with the node named: "Module" and the node under that as "originalModules" and then under that are the items like "Creating Results". These items are what I want to put in the array and then into the table view... does that help anyone??? – theGuiza Mar 30 '17 at 23:50
  • Please post a snippet of your Firebase structure, as text please no images. You can get the text via the Firebase console->Three dots in upper right corner->Export JSON. – Jay Mar 31 '17 at 12:47
  • { "Module" : { "originalModules" : { "CreatingResults" : "Creating Results", "EffectiveCommunication" : "Effective Communication", "PresentationSkills" : "Presentation Skills", "ProblemSolving" : "Problem Solving", "SelfAwareness" : "Self Awareness", "Teamwork" : "Teamwork" } }, "posts" : { "-KcTZfFT58IPT5ZJJRPX" : { "caption" : "hello?", "imageUrl" : "https://firebasestorage.googleapis.com", "likes" : 1 }, } – theGuiza Mar 31 '17 at 15:15
  • @Jay is that what you were looking for? looks a little messy... the first node - "Module" is what I am querying and having problems with. The node "posts" is for another part of my app and that works fine and is the data structure for the code that works and so I included it for reference... if that makes sense – theGuiza Mar 31 '17 at 15:20
  • lol. uh, no. *Update your question* with the structure - that will make it readable. – Jay Mar 31 '17 at 17:56

0 Answers0