简体   繁体   English

无法从Firebase存储加载用户图像

[英]user images not loading from Firebase storage

when running this code I only get it returning UIImage(named: "Home Button") from assests and not each user's chosen picture? 当运行此代码时,我只会从assets而不是每个用户选择的图片中返回UIImage(named: "Home Button") Any ideas why?? 任何想法为什么?

class usersScreenVC: UITableViewController {

let cellId = "cellId"

var users = [User]()

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))

    tableView.register(UserCell.self, forCellReuseIdentifier: cellId)

    fetchUser()
}

func handleCancel() {
    self.dismiss(animated: true, completion: nil)
}

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

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

            self.users.append(user)

            user.DisplayName =  dictionary["Display Name"] as? String
            user.SubtitleStatus = dictionary["SubtitleStatus"] as? String

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }, withCancel: nil)
}

override      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return users.count

}

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


           let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

    let user = users[indexPath.row]
    cell.textLabel?.text = user.DisplayName
    cell.detailTextLabel?.text = user.SubtitleStatus

    cell.imageView?.image = UIImage(named: "Home Button")

    if let profileImageURL = user.profileImageURL{
        let url = URL(string: profileImageURL)


       URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in     
            //this mean download hit an error so lets return out.
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async(execute: {     
                cell.imageView?.image = UIImage(data: data!)
            })      
        }).resume()
    }

    return cell
}

class UserCell: UITableViewCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}
}//class

There are about two issues with your code that I think might help. 我认为您的代码可能会涉及两个问题。 First of all, it is considered best practice to use SD WebImage when loading images from Firebase Storage. 首先,从Firebase Storage加载图像时,最好使用SD WebImage。 SD WebImage will deal with asynchronously loading images, caching images, guarantee that the same URL won't be downloaded several times and bogus URLs won't be retried. SD WebImage将处理异步加载图像,缓存图像,确保不会多次下载相同的URL,并且不会重试虚假的URL。 SD WebImage comes with Firebase so all you need to do to make it work is to make sure you have added Storage to your PodFile and to create an import for SDWebImage and FirebaseStorage in your TableViewController. SD WebImage随Firebase一起提供,因此要使其正常工作,只需确保已将Storage添加到PodFile中,并在TableViewController中为SDWebImage和FirebaseStorage创建导入。 Then you should modify your cellForRowAt indexPath to something like this: 然后,您应该将cellForRowAt indexPath修改为如下形式:

    import SDWebImage
    import FirebaseStorage 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


       let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)

       let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        let user = users[indexPath.row]
        cell.textLabel?.text = user.DisplayName
        cell.detailTextLabel?.text = user.SubtitleStatus

        cell.imageView?.image = UIImage(named: "Home Button")

        if let profileImageURL = user.profileImageURL{
        let url = URL(string: profileImageURL)

        cell.imageView?.sd_cancelCurrentImageLoad()

        cell.imageView?.sd_setImage(with: url, completed: { (image, error, type, url) in
        DispatchQueue.main.async {
        cell.layoutSubviews()
        }
    })      

}

return cell
}

Second of all, where are you setting the profile image for each user? 其次,您在哪里为每个用户设置个人资料图像? I can see you setting the display name and subtitle status but I cannot see where you are adding the profile image. 我可以看到您设置了显示名称和字幕状态,但看不到您要在其中添加个人资料图像的位置。 Perhaps you meant to do something like the following: 也许您打算执行以下操作:

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

        self.users.append(user)

        user.DisplayName =  dictionary["Display Name"] as? String
        user.SubtitleStatus = dictionary["SubtitleStatus"] as? String

        //did you forget to add the profile image url like this?
       user.profileImageURL = dictionary["ProfileImage"] as? String

        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}, withCancel: nil)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM