简体   繁体   English

如何使用 Firebase 将新照片上传到 collectionView 单元格?

[英]How would I upload new photo into collectionView cell using Firebase?

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此处的代码允许我将一张照片上传和下载到 Firebase 并将其保存为用户默认值,但我试图弄清楚如何在 collectionView 单元格中执行此操作并显示所需的照片数量,添加新项目

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

To upload images to Firebase storage and show them in a collection view, you can use the following steps;要将图像上传到 Firebase 存储并在集合视图中显示它们,您可以使用以下步骤;

  1. Set up collection view with an array of URL s (or String s) as its data source.使用URL s(或String s)的数组作为其数据源设置集合视图。 You can use your custom models if required.如果需要,您可以使用自定义模型。

  2. Keep a reference to your Firebase storage and upload the image.保留对您的Firebase storage的引用并上传图像。 After successful upload, get the URL for the uploaded image using the image reference .上传成功后,使用image reference获取上传图片的URL。

  3. Save the url in Firebase Database (or Cloud Firestore ).将 url 保存在Firebase Database (或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.仅当您希望将集合视图与数据库同步并在上传新图像时对其进行更新时,才需要这样做。

  4. Add a listener to your Firebase database reference where you have saved the image URLs.将侦听器添加到您保存图像 URL 的Firebase database引用。 Update the local URLs array inside the listener and reload the collection view.更新侦听器内的本地 URLs 数组并重新加载集合视图。

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.如果您不想使用Firebase database ,请省略步骤 3 和 4,将图像 URL 保存到数组并立即重新加载集合视图。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将带有 imagepickercontroller 的照片作为缩略图放入 collectionView 单元格 - how to get a photo with imagepickercontroller into the collectionView cell as thumbnail 如何水平和垂直滚动collectionview单元格..我正在使用9单元格collectionview - how to scroll collectionview cell horizontally and vertically..i am using 9 cell collectionview 将新单元格插入到集合视图中 - Inserting a new cell into a collectionview CollectionView-添加新单元格 - CollectionView - Adding a new cell 如何从项目的 collectionView 访问选定的单元格? // 项目存储 firebase - How can I access selected cell from collectionView of items? // items stored firebase 如何使用更少的内存在 collectionView 中显示照片库 - How to display photo library in collectionView using less memory 如何创建从collectionview单元到另一个collectionview单元的序列? - How can I create a segue from a collectionview cell to another collectionview cell? 使用 rx 在 collectionView 中单击时如何获取我的单元格? - How do I get ahold of my cell when clicking in collectionView using rx? Swift CollectionView 单元格中的 CollectionView 单元格 - 当前新视图 Controller - Swift CollectionView Cell in a CollectionView Cell - Present New View Controller 选择该单元格后,如何将其从图像库上传到特定的collectionview单元格? - How to upload image from photolibrary to specific collectionview cell when that cell is selected?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM