gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:11:27 25 4
gpt4 key购买 nike

此处的代码允许我将一张照片上传和下载到 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)
}
}

最佳答案

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

  • 使用 URL 的数组设置 Collection View s(或 String s)作为其
    数据源。如果需要,您可以使用自定义模型。
  • 保留对您的 Firebase storage 的引用并上传图片。上传成功后,使用image reference获取上传图片的URL .
  • 将网址保存在 Firebase Database 中(或 Cloud Firestore )。仅当您希望将 Collection View 与数据库同步并在上传新图像时对其进行更新时,才需要这样做。
  • 为您的 Firebase database 添加一个监听器引用你有的地方
    保存图像 URL。更新监听器内的本地 URLs 数组并重新加载 Collection View 。

  • 如果您不想使用 Firebase database ,省略步骤 3 和 4,将图像 URL 保存到数组并立即重新加载 Collection View 。
    我没有在此处添加 Collection View 设置的代码,因为这不是此答案的目标。
    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])
    }
    }

    }

    关于ios - 如何使用 Firebase 将新照片上传到 collectionView 单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63386722/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com