web-dev-qa-db-fra.com

Téléchargement d'image vers le stockage et la base de données Firebase

Je souhaite mettre l'URL de téléchargement des images dans ma base de données Firebase. Je peux télécharger l'image dans le stockage, mais je ne vois pas comment insérer l'URL dans ma base de données avec le reste de la "publication".

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

        }
    }
}
5
Riccardo

Organisez vos fonctions upload et save comme ceci:

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

Ensuite, connectez-vous à FIRDatabase et enregistrez-le sur votre nœud.

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

Vous pouvez également consulter ma réponse à propos du téléchargement de données et de l'enregistrement des URL dans la base de données

J'espère que ça aide

11
Vlad Pulichev
 //MARK: - Upload image
func uploadImage(_ image: UIImage){

    let imageName:String = String("\(CurrentTimeStampInSecond).png")

    let storageRef = Storage.storage().reference().child("profilePic").child(imageName)
    let compressImage = HelperFunction.helper.resizeImage(image: image)
    if let uploadData = UIImagePNGRepresentation(compressImage){
        storageRef.putData(uploadData, metadata: nil
            , completion: { (metadata, error) in
                if error != nil {
                    print("error")
                     self.stopAnimating()
                    showAlertWithTitleWithMessage(message: "Please try again later")
                    return
                }else{
                    self.stopAnimating()
                }

                let strPic:String = (metadata?.downloadURL()?.absoluteString)!

                print(metadata)
                //self.imagePath = (metadata?.downloadURL()?.absoluteString)!
                //self.sendMessageOnServer()
                print("\n\n\n\n\n\n ===download url : \(strPic)")

        })

    }
}
0
Mr.Javed Multani