SWIFT-为什么要发帖时总是出错?

时间:2018-08-08 10:42:46

标签: swift xcode firebase firebase-realtime-database

我做了一个类似于Twitter应用程序的项目。除此一项外,其他所有项目均有效。当我尝试共享内容时,总是会收到SIGBART错误。

@IBAction func post(_ sender: AnyObject) {
    let userID = Auth.auth().currentUser?.uid
    Database.database().reference().child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in



        let data = snapshot.value as! Dictionary<String, AnyObject>
        let username = data["username"]
        let userImg = data["userImg"]

        let post: Dictionary<String, AnyObject> = [
            "username": username as AnyObject,
            "userImg": userImg as AnyObject,
            "postText": self.postText.text as AnyObject
        ]

        let firebasePost = Database.database().reference().child("textPosts").childByAutoId()
        firebasePost.setValue(post)
    }) { (error) in
        print(error.localizedDescription)
    }
}

这是我的代码。 SIGBART位于“让数据=快照...”上

尽管我在控制台中遇到了这个问题: 无法将类型'NSNull'(0x104721850)的值强制转换为'NSDictionary'(0x104721288)。 (lldb)

2 个答案:

答案 0 :(得分:1)

您将获得空值,并且正在将其强制转换为字典。因此,您将崩溃。因此,请首先检查快照是否有子级,如下所述。

@IBAction func post(_ sender: AnyObject) {
    let userID = Auth.auth().currentUser?.uid
    Database.database().reference().child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
       if snapshot.childrenCount > 0 {
          let data = snapshot.value as! Dictionary<String, AnyObject>
          let username = data["username"]
          let userImg = data["userImg"]

          let post: Dictionary<String, AnyObject> = [
            "username": username as AnyObject,
            "userImg": userImg as AnyObject,
            "postText": self.postText.text as AnyObject
          ]

          let firebasePost = Database.database().reference().child("textPosts").childByAutoId()
          firebasePost.setValue(post)
       }
    }) { (error) in
        print(error.localizedDescription)
    }
}

答案 1 :(得分:1)

如果不确定当时属性是否有值,则最好不要使用as!情况下的强制展开。这就是Swift向我们提供Optional的原因。 试试这个:
guard let data = snapshot.value as? Dictionary<String, AnyObject> else { return }
而且对于代码可读性而言,将代码从@IBAction移至func updateDatabase(_ value: String, completion: () -> Void)之类的独立功能是一种更好的方法。