swift - 如何从 Firebase 获取图像并将其显示为 ImageView ?

标签 swift xcode firebase firebase-realtime-database

目前,我设置了一个 ImageView ,它引用并呈现我存储在 Assets 文件夹中的图像。如何让它从 Firebase 中提取用户图像?

lazy var profileImageView: UIImageView = {

    let imageView = UIImageView()
    imageView.image = UIImage(named: "profileUpload")
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    //imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))
    imageView.isUserInteractionEnabled = true
    return imageView

}()

该函数正在引用并拉取我需要提供的 profileImageUrl。我怎样才能将其添加到我之前的惰性变量中?

func fetchUser() {
    Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let user = User()

            user.profileImageUrl = dictionary["profileImageUrl"]as? String

        }

    }, withCancel: nil)
}

有没有办法通过用 imageView 替换 cell 来复制这个方法?这看起来容易得多,并且需要的代码也少得多。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell
    cell.textLabel?.textColor = UIColor.white
    let user = users[indexPath.row]
    cell.textLabel?.text = user.name
    cell.detailTextLabel?.text = user.email
    cell.detailTextLabel?.textColor = UIColor.white
    cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 15.0)

    if let profileImageUrl = user.profileImageUrl {
        cell.profileImageView.loadImageUsingCacheWithUrlString(profileImageUrl)
    }

    return cell
}

上面的代码在表格 View 中提取并呈现我需要的图像。

最佳答案

试试这个代码。

首先,创建customView类。

import UIKit

var imageCache = [String: UIImage]()

class CustomImageView: UIImageView {

var lastUrlUsedToLoadImage: String?

func loadImage(urlString: String) {
    lastUrlUsedToLoadImage = urlString

    //Image cache
    if let cachedImage = imageCache[urlString] {
        self.image = cachedImage
        return
    }

    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }

        if url.absoluteString != self.lastUrlUsedToLoadImage {
            return
        }

        guard let imageData = data else { return }
        let photoImage = UIImage(data: imageData)

        imageCache[url.absoluteString] = photoImage

        DispatchQueue.main.async {
            self.image = photoImage
        }

        }.resume()
}

}

接下来,创建您的 User 对象。

import Foundation

struct User {
    let uid: String
    let username: String
    let profileImageUrl: String

    init(uid: String, dictionary: [String: Any]) {
        self.uid = uid
        self.username = dictionary["username"] as? String ?? ""
        self.profileImageUrl = dictionary["profileImageUrl"] as? String ?? ""
    }
}

然后在你的 View Controller 中。

import UIKit
import Firebase

class UserProfileController: UICollectionViewController {

var user: User? {
  didSet {
    guard let profileImageUrl = user?.profileImageUrl else { return }
    profileImageView.loadImage(urlString: profileImageUrl)  
  }
}

lazy var profileImageView: CustomImageView = {
    let iv = CustomImageView()
    return iv
}()

override func viewDidLoad() {
    super.viewDidLoad()

    fetchUser()
}

func fetchUser() {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
        guard let userDictionary = snapshot.value as? [String: Any] else { return }
        self.user = User(uid: uid, dictionary: userDictionary)
    }) { (error) in
        print("Failed to fetch user for posts:", error)
    }
}

}

很高兴为您提供帮助...享受)

关于swift - 如何从 Firebase 获取图像并将其显示为 ImageView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083122/

相关文章:

ios - 防止 Share Extension 中的 UINavigationBar 继承主应用程序外观设置

ios - 类型 'UIApplication' 没有成员 'didBecomeActiveNotification'

ios - 为什么我的代码无法在我的字符串中找到数字?

iPhone Xcode 有没有办法在不加载模拟器的情况下测试方法?

android - 单个用户可以在 Firebase 身份验证中将多个电话号码链接到他的帐户吗?

swift - 在没有数据的情况下初始化 DictionaryLiteral

xcode - 如何从 SWIFT 中的字符串获取 MD5 哈希并制作桥头

objective-c - Xcode/clang : Why do some, 不是全部,我的标题给 "warning: no rule to process file xxx for architecture arm7"

javascript - 从 Firebase 列表中转换对象的正确方法?

android - 使用 android 在 firebase 数据库中搜索子节点