从 Firebase 存储中快速上传人物图像

Posted

技术标签:

【中文标题】从 Firebase 存储中快速上传人物图像【英文标题】:swift upload persons image from firebase storage 【发布时间】:2017-11-17 21:25:35 【问题描述】:

我的代码为每个人提供了一个资产图像作为图片,我将如何更改它以使其从 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

【问题讨论】:

【参考方案1】:

** 您需要先将资产图片发送到 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 也使用它。

希望对你有用

【讨论】:

我的火力库中充满了用户和图像以及图像 url 作为字符串 我不确定那里;虽然当模拟器加载所有图片时没有错误是 cell.imageView?.image = UIImage(named: "Home Button") 图像而不是选择的那个使用上一个 VC 上的图像选择器,我虽然可能等待加载但我等了 5 分钟 user.profileImageURL = dictionary["profileImageUrl"] as?字符串 觉得我错过了^ 如果您将观察者设置为子更改,则可能会发生这种情况,您需要将时间与图像一起存储,并且在获取时需要根据时间对数组进行排序。【参考方案2】:

我不见了

user.profileImageURL = 字典["profileImageUrl"] 作为?字符串

【讨论】:

【参考方案3】:
  let imageData = UIImageJPEGRepresentation(image , 0.0)
    let storage = Storage.storage()
    let uploadRef = storage.reference().child("images/\(UUID().uuidString).jpg")
    uploadRef.putData(imageData!, metadata: nil)  metadata,
        error in
        if error == nil 
            print("successfully uploaded Image")
            url = (metadata?.downloadURL()?.absoluteString)!
            print("AhmedRabie \(url)")
            self.activityIndecator.stopAnimating()

        
        else 
            print("UploadError \(String(describing: error))")
        

    

【讨论】:

以上是关于从 Firebase 存储中快速上传人物图像的主要内容,如果未能解决你的问题,请参考以下文章

将图像上传到 Firebase 存储

将多个图像存储到 Firebase 并获取 url

如何将图像从颤动的资产上传到firebase存储?

从颤振上传图像到firebase存储

将图像从 ReactJS 上传到 Firebase v9 存储

无法从 python 服务器将图像上传到 Firebase 存储