将图像上传到 Firebase 存储和数据库 [英] Uploading Image to Firebase Storage and Database

查看:27
本文介绍了将图像上传到 Firebase 存储和数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像的下载 URL 放入我的 Firebase 数据库中.我可以将图像上传到存储中,但我不知道如何将 URL 与帖子"的其余部分一起输入到我的数据库中.

I want to put the download URL of images into my Firebase Database. I can upload the Image into storage but I can't figure out how to get the URL into my database with the rest of the "post".

@IBOutlet weak var titleText: UITextField!
@IBOutlet weak var authorText: UITextField!
@IBOutlet weak var mainText: UITextView!
@IBOutlet weak var dateText: UITextField!
@IBOutlet weak var myImageView: UIImageView!

var ref:FIRDatabaseReference?

override func viewDidLoad() {
    super.viewDidLoad()

    ref = FIRDatabase.database().reference()

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


@IBAction func uploadImage(_ sender: Any) {


       let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary

    image.allowsEditing = false

    self.present(image, animated: true)
    {
        //after its completed
    }
}


@objc(imagePickerController:didFinishPickingMediaWithInfo:) func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    {
        myImageView.image = image

    }
    else
    {
        //error
    }

    self.dismiss(animated: true, completion: nil)

    let storageRef = FIRStorage.storage().reference().child("myImage.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView.image!){
        storageRef.put(uploadData, metadata: nil, completion:
            {
                (metadata, error) in
                if error != nil {
                    print("error")
                    return
                }

   print(metadata)

   //how do I put the download URL in the metadata into my database

        }  
        )
    }

}

@IBAction func addPost(_ sender: Any) {

    if self.titleText.text != "" && self.authorText.text != "" && self.mainText.text != "" && self.dateText.text != ""
    {

        ref?.child("Posts").childByAutoId().setValue(["Title": titleText.text,"Article": mainText.text, "Author": authorText.text, "Date": dateText.text, "myImageURL": myImageURL])

        //the myImageURL part is where I get an error

        self.performSegue(withIdentifier: "post", sender: self)

    }
    else{

        let alertController = UIAlertController(title: "Oops!", message: "Field left blank", preferredStyle: .alert)

        let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
        alertController.addAction(defaultAction)

        self.present(alertController, animated: true, completion: nil)

        }
    }
}

推荐答案

像这样组织你的 uploadsave 功能:

Organize your upload and save funcs like this:

func uploadMedia(completion: @escaping (_ url: String?) -> Void) { 
    let storageRef = FIRStorage.storage().reference().child("myImage.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView.image!) {
        storageRef.put(uploadData, metadata: nil) { (metadata, error) in
            if error != nil {
                print("error")
                completion(nil)
            } else {
                completion((metadata?.downloadURL()?.absoluteString)!)) 
                // your uploaded photo url.
            }
       }
 }

接下来只需连接到 FIRDatabase 并将其保存到您的节点.

Next just connect to FIRDatabase and save it to your node.

 @IBAction func addPost(_ sender: Any) {
     if self.titleText.text   != "" && self.authorText.text != "" 
        && self.mainText.text != "" && self.dateText.text   != "" {
     
     uploadMedia() { url in 
          guard let url = url else { return }
          ref?.child("Posts").childByAutoId().setValue([
                                "Title"      : titleText.text,
                                "Article"    : mainText.text, 
                                "Author"     : authorText.text, 
                                "Date"       : dateText.text, 
                                "myImageURL" : url
                                ])
     }
 }

您还可以查看我的回答关于上传数据和将 URL 保存到数据库

You can also look at my answer about uploading data and saving URL's to database

这篇关于将图像上传到 Firebase 存储和数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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