Home > Software engineering >  Swift and Firebase - Receiving image from the user then uploading it to firebase
Swift and Firebase - Receiving image from the user then uploading it to firebase

Time:02-10

I want the user to upload an image from the photos library along with more input so I can write it to my database. I made an object with the received data from the user and I uploaded it (using ".child()") to firebase realtime database, but then I had to add the photo to the object so I used the UIImagePicker to upload the photo then I got stuck. my problem is that i don't know what type of info I should get from the image so I can add it to the object. I'm not sure if using an object is the right choice but since the data I’m adding is related to a specific item I thought it would be suitable.

// The object

 let object: [String : Any] = ["areaname": areaName! as Any ,"spotNo": spotNo, "loactionLat": areaLat, "locationLong": areaLong]
    database.child("Areas").child("Area_\(Int.random(in: 0..<100))" ).setValue(object)

@IBAction func chooseImageButton() {
    print("Add image button was pressed")
    let vc = UIImagePickerController()
    vc.sourceType = .photoLibrary
    vc.delegate = self
    vc.allowsEditing = true
    present(vc, animated: true)
 
}


extension AddAreaViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediawithInfo info: [UIImagePickerController.InfoKey : Any]) {
    print("\(info)")
    if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage {
    }
    
    picker.dismiss(animated: true, completion: nil) }

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}

}

Firebase structure

CodePudding user response:

My solution is saving the image using FirebaseStorage. And turn the image url to string write into database. When you need loading image. You can search by that urlstring.

CodePudding user response:

I think @Evan Lu is correct. You don't need to store the image on firebase database or realtime databse. You can store the image on FirebaseStorage and save the url on database.

  • Related