[英]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 存储并在集合视图中显示它们,您可以使用以下步骤;
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.如果需要,您可以使用自定义模型。
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。
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.仅当您希望将集合视图与数据库同步并在上传新图像时对其进行更新时,才需要这样做。
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.