快速将多个图像从集合视图保存到Firebase存储中并获得downloadURL?

时间:2019-06-16 17:55:04

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

enter image description here,请帮助我将uicollectionview中的多张图片上传到firebase存储,并在实时数据库中显示downloadURL

我已经尝试了很多搜索,但是对我没有用。

我可以从libray导入图片并将其显示在myCollectionView中,但是我不知道如何将其保存到firebase中。

Reports
     -(userID)
        -(reportID) - Using childByAutoId
            - where i want to save to image

import UIKit
import Firebase

class ProblemViewController: UIViewController, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    var reportID : String!
    var phonNumber : String!

    var ref: DatabaseReference!
    let storage = Storage.storage()
    let userID = Auth.auth().currentUser!.uid

    @IBOutlet weak var problemButton: UIButton!
    @IBOutlet weak var myCollectionView: UICollectionView!

    @IBOutlet weak var problemImage: UIImageView!

    var images = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.myCollectionView.delegate = self
        self.myCollectionView.dataSource = self

        retrieveUser()
        generateReportID()

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(importPicture))

    }

    @IBAction func sendProblemAction(_ sender: Any) {
        //TODO: Storage image and Send information to Firebase and save it in our database
        let imageName = UUID().uuidString
        let storageRef = storage.reference().child("product_images/\(userID)/report/\(imageName).jpg")
        if let uploadImage = problemImage.image!.jpegData(compressionQuality: 0.15) {

            storageRef.putData(uploadImage, metadata: nil) { (metadata, error) in
                if error != nil {
                    print("error")
                    return
                }

                storageRef.downloadURL(completion: {(url, error) in
                    if error != nil {
                        print(error!.localizedDescription)
                        return
                    }
                    let downloadURL = url?.absoluteString

                    let post = ["report_image_url": downloadURL!] as [String : Any]

                    self.registerUserIntoDatabase(userID: self.userID, values: post as [String : AnyObject])

                })
            }
        }
        self.navigationController?.popToRootViewController(animated: true)
    }

    private func registerUserIntoDatabase(userID: String, values: [String:AnyObject]){
        //TODO: Send information to Firebase and save it in our database
        ref = Database.database().reference()
        let usersRef = ref.child("Reports").child("\(userID)/\(reportID!)")
        usersRef.updateChildValues(values, withCompletionBlock: { (err, ref) in
        })
    }

    func generateReportID () {
        ref = Database.database().reference()
        guard let key = self.ref.child("Reports").child("\(userID)/\(String(describing: reportID))").childByAutoId().key else { return }
        reportID = key
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageView", for: indexPath)

        if let imageView = cell.viewWithTag(1000) as? UIImageView {
            imageView.image = images[indexPath.item]
        }
        return cell
    }

    @objc func importPicture() {
        let picker = UIImagePickerController()
        picker.allowsEditing = true
        picker.delegate = self

        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        actionSheet.addAction(UIAlertAction(title: "picture", style: .default, handler: { (action) in
            picker.sourceType = .photoLibrary
            self.present(picker, animated: true, completion: nil)
        }))

        actionSheet.addAction(UIAlertAction(title: "cancel", style: .default, handler: nil))
        self.present(actionSheet, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[.editedImage] as? UIImage else { return }

        dismiss(animated: true)

        images.insert(image, at: 0)
        myCollectionView.reloadData()
        print("key = \(image)")
    }
}

我想将显示在uicollectionview中的多个图像上传到我的Firebase存储中,并在实时数据库中显示downloadURL。

像这样

Reports
     -(userID)
        -(reportID) - Using childByAutoId
            - image1 : "https://firebasestorage.googleapis.com/..."
            - image2 : "https://firebasestorage.googleapis.com/..."
            - image3 : "https://firebasestorage.googleapis.com/..."
            - image4 : "https://firebasestorage.googleapis.com/..."

My UICollection   当我按Save时,将出现这样的错误

My error

0 个答案:

没有答案
相关问题