2

I have a profile picture stored in my firebase storage for each user. Here is the reference:

profilePicRef = FIRStorage.storage().reference().child((FIRAuth.auth()?.currentUser.uid)!+"/profile_pic.jpg")

I want to be able to access the picture from my storage and put it into my database using this path:

@IBAction func Post(_ sender: AnyObject) {

   let postObject: Dictionary<String, Any> = [

         "userpic" : ""
    ]

FIRDatabase.database().reference().child("posts").child(self.loggedInUser!.uid).childByAutoId().setValue(postObject)

 }

I am unclear as to what goes into the quotation marks next to "userpic"

juelizabeth
  • 485
  • 1
  • 8
  • 31

1 Answers1

1

The database itself is not ideal for storing photos (however you could technically do a base64 encoding of an image, which might be better if the images are very small).

What I've found works best for profile images is to store them Firebase storage based on the UID. When I want to upload an image, I resize it first:

// from https://stackoverflow.com/a/29138120/1822214.  Only for square images.
func resizeWith(_ width: CGFloat) -> UIImage? {
    let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
    imageView.contentMode = .scaleAspectFit
    imageView.image = self
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
    guard let context = UIGraphicsGetCurrentContext() else { return nil }
    imageView.layer.render(in: context)
    guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
    UIGraphicsEndImageContext()
    return result
}

and then I upload it like so:

    func uploadProfilePic(_ uid: String, image: UIImage?, completion: @escaping (Bool) -> ())
        // compress with moderate quality (between 0 and 1)
        let data: Data = UIImageJPEGRepresentation(image!, 0.5)!
        let profileRef = storageRef.child("users/\(uid)/profile.jpg")

        let metadata = FIRStorageMetadata()
        metadata.contentType = "image/jpg"

        // Upload the file
        let uploadTask = profileRef.put(data, metadata: metadata) { metadata, error in
            if (error != nil) {
                // Uh-oh, an error occurred!
                print("there was an error uploading the profile pic!")
                print(error)
                // completion with failure... :(
                completion(false)
            } else {
                // Metadata contains file metadata such as size, content-type, and download URL.
                let downloadURL = metadata!.downloadURL
                // completion with success!
                completion?(true)
            }
        }
    }

I hope this can get you started, let me know if you've got any questions.

Community
  • 1
  • 1
Forest Kunecke
  • 2,160
  • 15
  • 32