我有一个应用程序,用户在其中拍摄一些保存到阵列中的图片,然后当他按下按钮时,我希望将图像阵列保存到Firebase。我到处搜寻,却找不到任何好的资源。贝娄是我已经编写的代码。
我保存图像数组的DataModel:
import Foundation
import UIKit
class PhotoArray {
static let sharedInstance = PhotoArray()
var photosArray: [UIImage] = []
}
拍摄图片代码:
import UIKit
import RealmSwift
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// var realm: Realm!
// var photoArray = [PhotoArray]()
@IBOutlet weak var imageView: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// realm = try! Realm()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let userPickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// let imageToUse = PhotoArray()
// let data = UIImagePNGRepresentation(userPickedImage) //here convert to data
PhotoArray.sharedInstance.photosArray.append(userPickedImage) //append converted data in array
// do {
// try realm.write {
// realm.add(imageToUse)
// }
// } catch {
// print(“error adding image to array\(error)“)
// }
imageView.image = userPickedImage
}
// print(PhotoArray().photosArray.count)
imagePicker.dismiss(animated: true, completion: nil)
}
@IBAction func cameraButtonPressed(_ sender: UIButton) {
present(imagePicker, animated: true, completion: nil)
}
@IBAction func cameraButtonPressed(_ sender: UIButton) {
present(imagePicker, animated: true, completion: nil)
}
@IBAction func SendDataPressed(_ sender: UIButton) {
//TODO: Send the Images to Firebase and save it in our database
let messagesDB = Database.database().reference().child("Images")
let messageDictionary = ["Images": PhotoArray.sharedInstance.photosArray as NSArray]
messagesDB.childByAutoId().setValue(messageDictionary) {
(error, refrence) in
if error != nil {
print(error!)
//somthing
}
else {
print("message saved succesfully")
//somthing
}
}
}
}
答案 0 :(得分:2)
Firebase数据库不支持将图像添加到数据库。您可以找到受支持的Firebase数据类型here。
您应该将图像上传到Firebase Cloud Storage之类的存储提供商,然后将该URL保存到数据库中的该文件中,以供日后下载。
这是一个例子:
//Create a reference to the image
let imageRef = Storage.storage().reference().child("image.jpg")
// Get image data
if let uploadData = UIImagePNGRepresentation(userPickedImage) {
// Upload image to Firebase Cloud Storage
imageRef.putData(uploadData, metadata: nil) { (metadata, error) in
guard error == nil else {
// Handle error
return
}
// Get full image url
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Handle error
return
}
// Save url to database
Firestore.firestore().collection("images").document("myImage").setData(["imageUrl" : downloadUrl.absoluteString])
}
}
}