如何使用Firebase将新照片上传到collectionView单元中? [英] How would I upload new photo into collectionView cell using Firebase?

查看:103
本文介绍了如何使用Firebase将新照片上传到collectionView单元中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的代码允许我将一张照片上传并下载到Firebase并将其保存为用户默认设置,但我试图弄清楚如何在collectionView单元中进行操作并显示所需的照片,并添加新项目

The code here allows me to upload and download one photo to Firebase and save it to user defaults but I'm trying to figure out how to do it within a collectionView cell and display as many photos wanted, adding on new items

    import UIKit
    import FirebaseStorage
    
        class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        
            private let storage = Storage.storage().reference()
            
            @IBOutlet var imageView: UIImageView!
            @IBOutlet var label: UILabel!
            
        override func viewDidLoad() {
                super.viewDidLoad()
                // Do any additional setup after loading the view.
                label.numberOfLines = 0
                guard let urlString = UserDefaults.standard.value(forKey: "url") as? String, let url = URL(string: urlString) else {
                    return
                }
                label.text = urlString
                let task = URLSession.shared.dataTask(with: url, completionHandler: { data,_,error in
                    guard let data = data, error == nil else {
                        return
                }
                DispatchQueue.main.async {
                    let image = UIImage(data: data)
                    self.imageView.image = image
                    }
            })
                task.resume()
        }
            @IBAction func didTapButton() {
                let picker = UIImagePickerController()
                picker.sourceType = .photoLibrary
                picker.delegate = self
                picker.allowsEditing = true
                present(picker, animated: true, completion: nil)
            }
            func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
                picker.dismiss(animated: true, completion: nil)
                guard let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {
                    return
                }
                guard let imageData = image.pngData() else {
                    return
                }
                storage.child("Images/Photo.png").putData(imageData, metadata: nil) { (_, error) in
                    guard error == nil else {
                        print("Failed to Upload Data")
                        return
                    }
                    self.storage.child("Images/Photo.png").downloadURL(completion: {url, error in
                        guard let url = url, error == nil else {
                            return
                        }
                        let urlString = url.absoluteString
                        DispatchQueue.main.async {
                            self.label.text = urlString
                            self.imageView.image = image
                        }
                        print("Download URL: \(urlString)")
                        UserDefaults.standard.set(urlString, forKey: "url")
                    })
                }
                // Upload Image Data
                // Get Download URL
                // Save Download URL to userDefaults
            }
            func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
                picker.dismiss(animated: true, completion: nil)
            }
        }

推荐答案

要将图像上传到Firebase存储并在集合视图中显示它们,您可以使用以下步骤;

To upload images to Firebase storage and show them in a collection view, you can use the following steps;

  1. 使用URL s(或String s)数组作为设置集合视图 数据源.您可以根据需要使用自定义模型.

  1. Set up collection view with an array of URLs (or Strings) as its data source. You can use your custom models if required.

保留对您的Firebase storage的引用并上传图像.成功上传后,使用image reference获取上传图像的URL.

Keep a reference to your Firebase storage and upload the image. After successful upload, get the URL for the uploaded image using the image reference.

将URL保存在Firebase Database(或Cloud Firestore)中.仅当您要将集合视图与数据库同步并在上传新图像时对其进行更新时,才需要这样做.

Save the url in Firebase Database(or Cloud Firestore). This is required only if you want to sync the collection view with the database and update it when new images are uploaded.

在您的Firebase database参考中添加一个侦听器 保存了图片网址.更新侦听器内部的本地URL数组,然后重新加载集合视图.

Add a listener to your Firebase database reference where you have saved the image URLs. Update the local URLs array inside the listener and reload the collection view.

如果不想使用Firebase database,则省略步骤3和4,将图像URL保存到数组中,并立即重新加载集合视图.

If you don't want to use Firebase database, omit steps 3 and 4, save the image URL to the array and reload the collection view right away.

我不是在这里添加用于集合视图设置的代码,因为这不是此答案的目的.

I'm not adding the code for collection view setup here as it's not the objective of this answer.

let storageRef = Storage.storage().reference(withPath: "images")
let databaseRef = Database.database().reference(withPath:"images")
var images: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()
    
    addDatabaseListener()
}

private func addDatabaseListener() {
    databaseRef.observe(.childAdded) { (snapshot) in
        
        guard let value = snapshot.value as? [String: Any], let url = value["url"] as? String else { return }
        self.images.append(url)
        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
    }
}


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

    let fileName = "\(Date.timeIntervalSinceReferenceDate).jpeg"
    let newImageRef = storageRef.child(fileName)
    
    newImageRef.putData(data, metadata: nil) { (_, error) in
        if let error = error {
            print("upload failed: ", error.localizedDescription)
            return
        }
        
        newImageRef.downloadURL { (url, error) in
            if let error = error {
                print("error: ", error.localizedDescription)
                return
            }
            self.databaseRef.childByAutoId().setValue(["url": url?.absoluteString])
        }
    }
    
}

这篇关于如何使用Firebase将新照片上传到collectionView单元中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆