ios - 从firebase存储中快速上传人物图像

标签 ios swift firebase firebase-realtime-database firebase-storage

我的代码提供了一个 Assets 图像作为每个人的图片,我如何更改它以使其从 firebase 检索每个人的图像?

import UIKit
import Firebase

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

最佳答案

** 您需要先将 Assets 图像发送到 firebase **

在您要发送图像的位置调用此函数

  func uploadImageToFB (image : UIImage){
                
                let imageData = UIImageJPEGRepresentation(image, 1.0)
                let metadata = StorageMetadata()
                metadata.contentType = "image/jpeg"
                let imagePath = Auth.auth().currentUser!.uid + "/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
    
       //StorageRef is FIRDatabaseRefrence here you need to pass your storage url given in Firebase Console //
    
                storageRef.child(imagePath).putData(imageData!, metadata: metadata, completion: { (metadata, error) in
                    if let error = error {
                        print("Error uploading photo: \(error)")
                        return
                    }else{
                        let autoID = self.ref.childByAutoId().key
                        print(metadata ?? "")
                        let userID : String = Auth.auth().currentUser!.uid
                        let ImageRef : DatabaseReference = self.statusRef.child(userID)
                    
                        let imageUrls = [
                            "imageUrl" : metadata?.downloadURL()?.absoluteString
                            ] as [String : Any]
                        let userInfo = ["UserID":userID,
                                       "userName":Auth.auth().currentUser!.displayName]

   //Here Image Ref is FIRDatabaseRefrence upto the node you need to set your image 
           
    ImageRef.child("UserInfo").updateChildValues(userInfo)
                  
   ImageRef.child("Images").child(autoID).setValue(imageUrls)
                    }
                })
            }

现在,当从 firebase 获取时,您的 imageurl 也会使用它。

希望它对您有用

关于ios - 从firebase存储中快速上传人物图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44566574/

相关文章:

firebase - 如何将数据从谷歌云 pubsub 获取到 firebase 实时数据库

ios - 从另一个 ViewController 访问数组并对其进行排序

ios - 在 Objective-C 中计算广播地址

ios - 如何使用 FileManager 在 iOS 中写入文件?

swift - UISearchController 中的取消按钮在 iOS 13 中没有正确消失

reactjs - 如何查找 v3.0.0 是否支持 firebaseAuthIsReady?

ios - 使用 UIWebView 播放视频时出错

ios - 如何将 ipa 文件临时部署到我的 iPhone

iphone - 如何从 UIViewController 访问 UINavigationController

ios - 如何在没有动画的情况下执行 unwind segue?