如何将打印的项目添加到Firebase数据库?

时间:2017-05-23 23:39:48

标签: ios swift firebase firebase-realtime-database

我正在尝试将打印的项目与其余的插件一起插入我的Firebase数据库。谢谢!

@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
                } else {
                    print((metadata?.downloadURL()?.absoluteString)!)
                   //i want to take the line above and insert it into the 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 ])

        //insert the download URL above 
        self.performSegue(withIdentifier: "kost", sender: self)    
    }
}

1 个答案:

答案 0 :(得分:0)

我现在看到你的问题了。您正在以完全错误的方式处理将图像上传到firebase。在事件didFinishPickingMediaWithInfo中,您不应该使用firebase做任何事情。您应该只设置UIImageViews图像来存储图像选择器给出的数据值。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    self.dismiss(animated: true, completion: nil)
    if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage{
        myImageView.image = editedImage
    }else{
        print("Something went wrong")
    }
}

然后在您的IBAction中,您应该将所有内容上传到firebase。这是一个简单的函数,可以将您的图像上传到数据库:

func uploadImage(){
    if let fileData = UIImageJPEGRepresentation(myImageView.image!, 0.8){
    let storageRef = storage.reference().child("images").child("testImage.jpg")
        storageRef.put(fileData, metadata: nil, completion: { (metadata, error) in
            if error != nil{
                print(error?.localizedDescription ?? "error")
                return
            }
            let downloadURL = metadata?.downloadURL()?.absoluteString
            // Write the download URL to your Database
            self.ref?.child("images").setValue(downloadURL)
        })
    }else{
        print("error")
    }
}