从Firebase检索数据等于意外的nil - swift

时间:2016-11-24 13:59:05

标签: ios swift uitableview firebase firebase-realtime-database

我得到了最奇怪的错误,我不知道如何解决它.. 我有一个Firebase数据库,其中包含用户发布的所有帖子。它们存储在feed-items下。每当用户发布新帖子时,帖子都会添加到feed-items,并且Feed-items中的帖子键(autoId)会添加到用户拥有的每个关注者中。

如果我在UITableView中显示来自feed-items的所有帖子,那么根本没有问题。如果我尝试显示与用户个人墙中存储的密钥相同的帖子(当我关注的用户发布帖子时添加的密钥),那么我在unexpectedly found nil while unwrapping an optional中发现了一个奇怪的错误Sweet {1}} struct?

让我先向您展示两个代码,另一个代码不是:

工作代码:

func observePosts(userID: String) {
//        let ref = FIRDatabase.database().reference().child("Users").child(userID).child("Wall")
//        ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in
//            
//            let postId = snapshot.key
            let postReference = FIRDatabase.database().reference().child("feed-items")//.child(postId)

            postReference.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
                print(snapshot)
                var newUpdates = [Sweet]()
                    for update in snapshot.children {
                        let postUpdates = Sweet(snapshot: update as! FIRDataSnapshot)
                        newUpdates.append(postUpdates)
                    }
                    self.updates = newUpdates.reverse()

                    dispatch_async(dispatch_get_main_queue(), {
                       self.tableView.reloadData()
                    })
                }, withCancelBlock: nil)
            //}, withCancelBlock: nil)
    }

不工作代码:

func observePosts(userID: String) {
        let ref = FIRDatabase.database().reference().child("Users").child(userID).child("Wall")
        ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in

            let postId = snapshot.key
            let postReference = FIRDatabase.database().reference().child("feed-items").child(postId)

            postReference.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
                print(snapshot)
                var newUpdates = [Sweet]()
                    for update in snapshot.children {
                        let postUpdates = Sweet(snapshot: update as! FIRDataSnapshot)
                        newUpdates.append(postUpdates)
                    }

                    self.updates = newUpdates.reverse()

                    dispatch_async(dispatch_get_main_queue(), {
                       self.tableView.reloadData()
                    })
                }, withCancelBlock: nil)
            }, withCancelBlock: nil)
    }

应用程序崩溃的地方和我收到错误的行在我的结构中,在likesForPost下

MY STRUCT

import Foundation
import FirebaseDatabase
import FirebaseAuth
import UIKit

struct Sweet {
    let key: String!
    let content: String!
    let addedByUser: String!
    let profilePhoto: String!
    var likesForPost : [String:AnyObject]
    let itemRef: FIRDatabaseReference?
    let path : String!
    let date: String!
    let category: Int!
    let workoutComment: String!
    let workoutTime: String!


    init (content: String, addedByUser: String, profilePhoto: String!, likesForPost : [String:AnyObject]!, date: String, category: Int, workoutComment: String, workoutTime: String, key: String = "") {
        self.key = key
        self.content = content
        self.addedByUser = addedByUser
        self.profilePhoto = profilePhoto
        self.likesForPost = likesForPost
        self.itemRef = nil
        // self.path = dataPath
        self.path = ""
        self.date = date
        self.category = category
        self.Comment = Comment
        self.Time = Time
    }

    init (snapshot: FIRDataSnapshot) {
        key = snapshot.key
        itemRef = snapshot.ref
        path  = key
        if let theFeedContent = snapshot.value!["content"] as? String {
            content = theFeedContent
        } else {
            content = ""
        }

        if let feedUser = snapshot.value!["addedByUser"] as? String {
            addedByUser = feedUser
        } else {
            addedByUser = ""
        }

        if let feedPhoto = snapshot.value!["profilePhoto"] as? String! {
            profilePhoto = feedPhoto
        } else {
            profilePhoto = ""
        }

        if let feedLikes = snapshot.value!["likesForPost"] as? [String:AnyObject]! {
            likesForPost = feedLikes
        } else {
            likesForPost = ["":""]
        }

        if let feedDate = snapshot.value!["date"] as? String! {
            date = feedDate
        } else {
            date = ""
        }

        if let feedCategory = snapshot.value!["category"] as? Int! {
            category = feedCategory
        } else {
            category = 0
        }

        if let feedComment = snapshot.value!["Comment"] as? String! {
            Comment = feedComment
        } else {
            Comment = ""
        }

        if let feedTime = snapshot.value!["Time"] as? String! {
            Time = feedTime
        } else {
            Time = ""
        }

    }

    func toAnyObject() -> AnyObject {
        return ["content":content, "addedByUser":addedByUser, "profilePhoto":profilePhoto!, "likesForPost":likesForPost, "date":date, "category":category, "Comment":Comment, "Time":Time]
    }
}

我知道这是一篇很长的帖子,但如果你花时间帮助我,我会很高兴 - 我完全迷失了! :(

修改 这就是日志给我的东西:

Snap (-KXLGyWMljc2UNeRL1a3) {
    addedByUser = "Maja P";
    category = 1;
    content = Hejehjehj;
    date = "Nov,24,,2016,,1:20";
    likesForPost =     {
        "user id" = 0;
    };
    profilePhoto = VGpbOweP4jO2seeLNCGiv1p08jq1;
    Comment = "";
    Time = "";
}
fatal error: unexpectedly found nil while unwrapping an Optional value

这是完全正确的,但有两个帖子只打印上面的那个。

1 个答案:

答案 0 :(得分:2)

由于您在第二个代码中直接获得了帖子的DataSnapshot,因此我认为您不需要重复snapshot

尝试将代码更改为此代码,看看它是否有效。

func observePosts(userID: String) {
    let ref = FIRDatabase.database().reference().child("Users").child(userID).child("Wall")
    ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in

        let postId = snapshot.key
        let postReference = FIRDatabase.database().reference().child("feed-items").child(postId)

        postReference.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            print(snapshot)
                let update = Sweet(snapshot: snapshot)
                self.updates.insert(update, atIndex: 0)

                dispatch_async(dispatch_get_main_queue(), {
                   self.tableView.reloadData()
                })

            }, withCancelBlock: nil)

        }, withCancelBlock: nil)
}