swift - 将个人资料图像字符串从 firebase 数据库下载到 uiimage

标签 swift firebase swift4 firebase-storage

用户将图像上传到firebase存储并将url字符串添加到firebase数据库中, 如何获取 firebase 数据库中的字符串并将其转换为 uiimage 以将其用作图像?

从数据库返回的字符串是这样的:

https://firebasestorage.googleapis.com/v0/b/ichatmessage.appspot.com/o/YNoodTnOSGXl6HkPoqhOPAopb8v1?alt=media&token=738771a5-53e3-46c2-b508-ad5cfa03e74e

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as! NewMessageCell
    let user = users[indexPath.row]
    cell.textLabel?.text = user.username
    cell.detailTextLabel?.text = user.email
    let currentID = Auth.auth().currentUser?.uid
    let databaseRef = Database.database().reference().child("users").child(currentID!)
    databaseRef.observe(.value) { (data) in
        let dictinoray = data.value as? [String: AnyObject]
        let profileImage = dictinoray!["profileimage"] as! String
        cell.imageView?.image = profileImage.toImage()
        print(profileImage)
    }
    return cell
}

扩展

  extension String {
func toImage() -> UIImage? {
    if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters){
        return UIImage(data: data)
    }
    return nil
}
}

最佳答案

我通过映射和使用存储 downloadurl 使用其他方式,它起作用了

          override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as! NewMessageCell
    let user = users[indexPath.row]
    cell.textLabel?.text = user.username
    cell.detailTextLabel?.text = user.email
        let storageref = Storage.storage().reference().child(user.userid)
    storageref.downloadURL { (imgurl, er) in
        let imagedata = try? Data.init(contentsOf: imgurl!)
        cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)!/2
        cell.imageView?.image = UIImage.init(data: imagedata!)
    }

关于swift - 将个人资料图像字符串从 firebase 数据库下载到 uiimage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54020257/

相关文章:

firebase - 如何在 firestore 字段中插入 firebase 存储图像

ios - Firestore - 添加带有子集合的文档的单一操作

ios - 如何在 ios 应用程序中检索 firebase 数据库中的数据?我的 JSON 数据如下所示,我想获取与问题文本 A...E 关联的每个值

ios - WKWebView 检查Web View 是否支持加载文件

Swift4 中的 JSONDecoder 来自嵌套 JSON

ios - 太多的文字将我的按钮推到屏幕下方

如果使用索引,Swift 可以更改用 let 声明的结构,但如果使用循环则不能

swift - 声明一个只能包含 ASCII 字符的 Swift 字符类型?

ios - 如何在函数中传递任何类或结构作为参数?

ios - 如何将信息从一个 IBAction 传输到另一个 IBAction