错误从对象数组swift中检索数据

时间:2017-05-17 17:44:25

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

我正在尝试在用户之间编写消息聊天记录。所以我想从我的消息数组中只检索特定数据。例如,当一个人发送文本消息时,我只想从我的消息数组中检索fromId,toId和text。当一个人发送图像时,我只想从fromId,toId和imageUrl中检索。当应用程序崩溃时,因为当一个人发送文本" imageUrl"是零,反之亦然发送图像,其中"文本"没有。有没有解决的办法?或者我必须创建2个单独的数组?提前致谢

消息数组

class Message {

    var fromId: String
    var text: String
    var toId: String
    var timeStamp: NSNumber?
    var imageUrl: String



    init(fromId: String, text: String, toId: String, timeStamp: NSNumber, imageUrl: String){


        self.fromId = fromId
        self.text = text
        self.toId = toId
        self.imageUrl = imageUrl

    }

    init(snapshot:FIRDataSnapshot) {

        self.fromId = (snapshot.value! as! NSDictionary)["fromId"] as! String!

        self.toId = (snapshot.value! as! NSDictionary)["toId"] as! String!

        self.text = (snapshot.value! as! NSDictionary)["text"] as! String!

        self.imageUrl = (snapshot.value! as! NSDictionary)["imageUrl"] as! String!


    }

firebase结构

{ "messages": {

"KkGAWnQhqnOx525vv2W": {

"fromId": tvyT6UF6mWZeewAJXt076qqt7ek2,
"toId": USk3w8ZPYlRhfDmEwWwtkMhzUNX2,
"text": "Hello"
},
"hujU6UF6mWZeewAJXt0": {

"fromId": tvyT6UF6mWZeewAJXt076qqt7ek2,
"toId": USk3w8ZPYlRhfDmEwWwtkMhzUNX2,
"imageUrl": "https://firebasestorage.googleapis.com/v0/b.."
}

用于检索数据的方法

var message = [Message]()

func observeMessages(){

    let ref = FIRDatabase.database().reference().child("user-messages").child(uid)

    ref.observe(.childAdded, with: { (snapshot) in


        let messageId = snapshot.key

        let messageReference = FIRDatabase.database().reference().child("messages").child(messageId)
        messageReference.observe(.value, with: { (snapshot) in


            for posts in snapshot.children{

                let message = Message(snapshot: posts as! FIRDataSnapshot )

                let chatPartnerId = message.chatPartnerId()

                self.messagesDictionary[chatPartnerId!] = message


                    self.messageTableView.reloadData()
                })
            }

    }, withCancel: nil)
}

1 个答案:

答案 0 :(得分:1)

它崩溃的原因是因为你在使用字典下标时强行包装值。您需要使用if letguard let来包装可选项,或者您可以使用默认值为空的Nil-Coalescing Operator,然后检查哪一个非空text或{{1} }。

image

另外,击球手选项是在您的留言对象中再添加一个键init(snapshot:FIRDataSnapshot) { let dictionary = snapshot.value as! [String:Any] self.fromId = dictionary["fromId"] as! String self.toId = dictionary["toId"] as! String self.text = dictionary["text"] as? String ?? "" self.imageUrl = dictionary["imageUrl"] as? String ?? "" } ,其值为typetext。让你的结构像这样。

image

之后获取type的值,并进行比较{ "messages": { "KkGAWnQhqnOx525vv2W": { "fromId": tvyT6UF6mWZeewAJXt076qqt7ek2, "toId": USk3w8ZPYlRhfDmEwWwtkMhzUNX2, "type" "text" "text": "Hello" }, "hujU6UF6mWZeewAJXt0": { "fromId": tvyT6UF6mWZeewAJXt076qqt7ek2, "toId": USk3w8ZPYlRhfDmEwWwtkMhzUNX2, "type" "image" "imageUrl": "https://firebasestorage.googleapis.com/v0/b.." } } } text

image

现在,当您访问此对象时,请检查其类型并根据它访问其属性text和imageUrl。