簡體   English   中英

從Firebase存儲快速上傳人員圖像

[英]swift upload persons image from firebase storage

我的代碼為每個人提供了一個資產圖片作為圖片,我將如何更改它以使其從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

**您需要先將資產圖片發送到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。

希望這對你有用

我不見了

user.profileImageURL = dictionary [“ profileImageUrl”]如?

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

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM