Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Profile Picture Firestore #76

Closed
DattaKansal opened this issue Feb 13, 2025 · 0 comments
Closed

Profile Picture Firestore #76

DattaKansal opened this issue Feb 13, 2025 · 0 comments
Assignees

Comments

@DattaKansal
Copy link
Contributor

DattaKansal commented Feb 13, 2025

You are going to allow users to add, delete and update profile pictures. This seems like a trivial task but it is not.

General flow:

  • In FireStore, in a user document there will be a field for profile picture. This will contain a link to a picture (not the actual picture). This link points to an image in storage.
  • In FirebaseStorage, we will be storing the images.

Whenever you're updating/deleting make sure you're changing the value in FireStore and FirebaseStorage.

Linking some more documentation below to help you get started:

  1. Look at "Storage" in Firebase console. All images will go under the "/images" folder
  2. If you want to learn more about Storage: https://youtu.be/YgjYVbg1oiA?si=50piLxY9ihtCfCcg
  3. Documentation from Firebase: https://firebase.google.com/docs/storage/ios/upload-files and https://firebase.google.com/docs/storage/ios/download-files and https://firebase.google.com/docs/storage/ios/delete-files

If you're working on the FireStore your task is going to be go to the profile picture field and store the image URL that is provided by FirebaseStorage. Think of how you'll handle cases where a user adds a profile picture, updates and deletes. You can have placeholders for the function that the FirebaseStrorage has for storing and getting a URL.

Work in ProfileViewModel()

Adding reference code from past semesters of iOS (reach out if this doesn't make sense)

  1. Given a URL getting the image.
func getImageFromURL(urlString: String, completion: @escaping (UIImage?) -> Void) {
    guard let url = URL(string: urlString) else {
            print("Invalid URL string: \(urlString)")
            completion(nil)
            return
        }
        URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                if let error = error {
                    print("Error loading image from URL: \(error.localizedDescription)")
                    completion(nil)
                } else if let data = data, let image = UIImage(data: data) {
                    completion(image)
                } else {
                    print("Could not load image from URL: \(urlString)")
                    completion(nil)
                }
            }
        }.resume()
    }
  1. Storing an image in FirebaseStorage and returning the URL you stored
func storeImageAndReturnURL(image: UIImage, completion: @escaping (URL?) -> Void) {
        guard let imageData = image.jpegData(compressionQuality: 0.8) else {
            completion(nil)
            return
        }
          // create random image path
        let imagePath = "images/\(UUID().uuidString).jpg"
        let storageRef = Storage.storage().reference()
        // create reference to file you want to upload
        let imageRef = storageRef.child(imagePath)
        //upload image
        DispatchQueue.main.async {
            let uploadTask = imageRef.putData(imageData, metadata: nil) { (metadata, error) in
                if let error = error {
                    print("Error uploading image: (error.localizedDescription)")
                    print("GANDEN FUNG BAD")
                    completion(nil)
                } else {
                    // Image successfully uploaded
                    imageRef.downloadURL { url, error in
                        if let downloadURL = url {
                            completion(downloadURL)
                        } else {
                            print("Error getting download URL: (String(describing: error?.localizedDescription))")
                        }
                    }
                }
            }
        }
    }
  1. Get and update profile pictures
func updateProfilePic(userID: String, image: UIImage, completion: @escaping (URL) -> Void) {
        storeImageAndReturnURL(image: image) { url in
            guard let imageURL = url else {
               print("Failed to get download URL")
                return
            }
            let userDocument = self.db.collection("USERS").document(userID)
            userDocument.updateData(["profilePicture": imageURL.absoluteString]) { error in
                if let error = error {
                    print("Error updating document: \(error.localizedDescription)")
                    return
                } else {
                    print("Document successfully updated with new profile picture URL")
                    completion(imageURL)
                }
            }
        }
    }
func getProfilePic(userID: String, completion: @escaping (UIImage?) -> Void) {
       let userDocument = db.collection("USERS").document(userID)
       userDocument.getDocument { (document, error) in
           if let document = document, document.exists, let data = document.data(), let urlString = data["profilePicture"] as? String {
               self.getImageFromURL(urlString: urlString) { image in
                   completion(image)
               }
           } else {
               print("Document does not exist or URL could not be retrieved")
               completion(nil)
           }
       }
   }
@sam-orouji sam-orouji self-assigned this Feb 13, 2025
@sam-orouji sam-orouji changed the title Profile Picture Firestone Profile Picture Firestore Feb 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

When branches are created from issues, their pull requests are automatically linked.

2 participants