Uploading Image to Firebase Storage and Database
For Updated Firebase Version And Swift 4.2 Code :
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.
}
}
}
}
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.
}
}
}
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
])
}
}
You can also look at my answer about uploading data and saving URL's to database
100% working tested just one add function
//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)")
})
}
}