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

问题描述 投票:0回答:1

目前我有一个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
}

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

swift xcode firebase firebase-realtime-database
1个回答
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)
    }
}

}

很高兴帮助...享受)

© www.soinside.com 2019 - 2024. All rights reserved.