如何从Firebase提取图像并将其显示为imageview?

时间:2018-08-29 17:25:24

标签: 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替换单元来复制此方法?看起来容易得多,所需的代码也少得多。

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
}

上面的代码在表格视图中提取并显示我需要的图像。

1 个答案:

答案 0 :(得分:0)

尝试此代码。

首先,创建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 ?? ""
    }
}

然后在您的视图控制器中。

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)
    }
}

}

很高兴为您提供帮助...