将图像上传到Firebase存储和数据库

时间:2017-05-19 02:34:34

标签: swift firebase swift3 firebase-realtime-database firebase-storage

我想将图片的下载网址放入我的Firebase数据库。我可以将图像上传到存储中,但我无法弄清楚如何使用“帖子”的其余部分将URL放入我的数据库。

@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 个答案:

答案 0 :(得分:11)

像这样组织您的uploadsave功能:

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并将其保存到您的节点。

 @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保存到数据库的my answer

希望有所帮助

答案 1 :(得分:2)

对于更新的Firebase版本和Swift 4.2代码:

 func uploadMedia(completion: @escaping (_ url: String?) -> Void) {

    let storageRef = Storage.storage().reference().child("\(Auth.auth().currentUser?.uid ?? "").png")
    if let uploadData = self.imgUploadView.image?.jpegData(compressionQuality: 0.5) {
        storageRef.putData(uploadData, metadata: nil) { (metadata, error) in
            if error != nil {
                print("error")
                completion(nil)
            } else {

                storageRef.downloadURL(completion: { (url, error) in

                    print(url?.absoluteString)
                    completion(url?.absoluteString)
                })

              //  completion((metadata?.downloadURL()?.absoluteString)!))
                // your uploaded photo url.


            }
        }
    }
}

答案 2 :(得分:0)

 //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)")

        })

    }
}

答案 3 :(得分:0)

可能为时已晚,但是我已经找到了使用Utility Class to Upload Images & Files to Firebase Storage的简单方法。您可以使用上述实用程序类通过一个方法调用来上传图像和文件。喜欢

if let data = image.pngData() { // convert your UIImage into Data object using png representation
      FirebaseStorageManager().uploadImageData(data: data, serverFileName: "your_server_file_name.png") { (isSuccess, url) in
             print("uploadImageData: \(isSuccess), \(url)")
       }
}

答案 4 :(得分:0)

  Use UIImagePNGRepresentation in swift 4.2 like this,

 if let uploadData = profileImageView.image?.pngData() {
                    storageRef.putData(uploadData, metadata: nil) { (metadata, error) in
                        if error != nil {

                        }
                    }
                }