简体   繁体   中英

swift upload persons image from firebase storage

My code delivers an asset image as the picture for each person, how would I change it to get it to retrieve each persons image from 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

** You need to send your asset image to firebase first **

Call this function where you are sending image

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

Now while fetching From firebase you will get your imageurl also use it.

Hope it works for you

i was missing

user.profileImageURL = dictionary["profileImageUrl"] as? String

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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