swift firebase从存储中获取图像并在JSQMessage Controller中显示

时间:2019-06-03 19:29:25

标签: swift firebase firebase-storage jsqmessagesviewcontroller

我想在Firebase存储中获取保存的图像。

我将URL保存在Firebase数据库的字符串值中

mediaUrl = url!.absoluteString

现在我要获取这张图片。

我观察了消息。

func observeMessages() {
    let query = Constants.refs.databaseChats.child(chatId).queryLimited(toLast: 50)

    _ = query.observe(.childAdded, with: { [weak self] snapshot in

        if  let data        = snapshot.value as? [String: String],
            let id          = data["sender_id"],
            let name        = data["name"],
            let timestamp   = data["timestamp"],
            let media       = data["media"],
            let text        = data["text"]?.encode(),
            !text.isEmpty
        {
            if media == "text" {
                if let message = JSQMessage(senderId: id, senderDisplayName: name, date: self!.dateFormatter.date(from: timestamp), text: text) {
                    self?.messages.append(message)
                    self?.finishReceivingMessage()
                }
            }
            else if media == "image" {
                let storageRef = Storage.storage().reference(withPath: text)
                storageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) -> Void in
                    if data != nil {
                        let image = UIImage(data: data!)
                        if let imageMessage = JSQMessage(senderId: id, senderDisplayName: name, date: self!.dateFormatter.date(from: timestamp), media: image as! JSQMessageMediaData) {
                            self?.messages.append(imageMessage)
                            print("image message")
                            self?.finishReceivingMessage()
                        }
                    }
                }
            }

        }
    })
}

如果媒体是图像,我要创建图像气泡,当文本是普通文本气泡时。 但是我在JSQMEssageViewController中没有图像。 什么地方出了错?有人可以帮我吗?

我在控制台中获得了网址:

https://firebasestorage.googleapis.com/v0/b/emmessenger-22.appspot.com/o/media%2FJzl0EUmjSvZZcpCd8Mdi8X9q87G2%2F03.06.2019%2021:26:39?alt=media&token=1c45feaf-0ed8-4f88-9c1f-13f4c6a8f3d4

然后在控制台上获得以下内容:

2019-06-03 21:28:21.092580+0200 EMMessenger[38502:554129] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: NSURLErrorDomain: -1003

谢谢

1 个答案:

答案 0 :(得分:1)

实际上,在这种情况下,您不需要调用getData函数。当您使用tableView时,我建议使用SDWebImage库以异步方式将图像加载到单元格上。一旦有了imageURL,只需在下面的方法中调用

yourImageView.sd_setImage(with: URL(string: "https://firebasestorage.googleapis.com/v0/b/emmessenger-22.appspot.com/o/media%2FJzl0EUmjSvZZcpCd8Mdi8X9q87G2%2F03.06.2019%2021:26:39?alt=media&token=1c45feaf-0ed8-4f88-9c1f-13f4c6a8f3d4"), placeholderImage: UIImage(named: "placeholder.png"))

最好让图书馆为您服务。