1

I am having a bit of an issue checking Firebase Storage when a user logs into my app. When a user logs in an image is created and stored successfully in Firebase database and storage, but every time a user logs out and logs back into the app the profileImage file (not the child value url string) is duplicated in Firebase Storage as a new and separate image file.

I would like the app when logging in to check the Firebase storage for the profileImage file, and if it exists then do not re-create that same image in storage. I understand the logic of checking Firebase for image and if does not exist, than create new image. I am just having some trouble with the syntax. Thanks for help in advance!

// login user with Facebook
func loginWithFacebook() {
    let accessToken = FBSDKAccessToken.current()
    guard let accessTokenString = accessToken?.tokenString else { return }

    let credentials = FIRFacebookAuthProvider.credential(withAccessToken: accessTokenString)
    FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in
        if error != nil {
            print("Something went wrong with our FB user: ", error ?? "")
            return
        }

        guard let uid = user?.uid else {
            return
        }

        let imageName = NSUUID().uuidString
        let storageRef = FIRStorage.storage().reference().child("profile_images").child("\(imageName).png")
        let photoUrl = user?.photoURL

        // check to see if current user already has stored image with URL
        if FIRStorage.storage().reference().child("profile_images").child("\(imageName).png") == nil {

            if let imageData = NSData(contentsOf: photoUrl!) {
                storageRef.put(imageData as Data, metadata:nil) {
                    (metadata, error) in

                    if error != nil {
                        print(error!)
                        return
                    } else {

                        if let profileImageUrl = metadata?.downloadURL()?.absoluteString {
                            let values = ["name": user!.displayName!, "email": user!.email!, "profileImageUrl": profileImageUrl]
                            self.registerUserWithUID(uid: uid, values: values as [String : AnyObject])
                        }
                    }
                }
            }
        } else {
            print("image already exists")
        }

        print("Successfully logged in with our user: ", user ?? "")
        self.delegate?.finishLoggingIn()

      })

private func registerUserWithUID(uid: String, values: [String: AnyObject]) {
    // create items in database upon creating user ---------------
    let ref = FIRDatabase.database().reference()
    let usersReference = ref.child("users").child(uid)
    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
        if err != nil {
            print(err!)
            return
        }
        print("user has been saved to Firebase database")
    })
}
AL.
  • 36,815
  • 10
  • 142
  • 281
user3708224
  • 1,229
  • 4
  • 19
  • 37

1 Answers1

1

I think the issue is with the "if" condition. You are referencing the location, but not checking with the actual data in that location.

You can implement that using .observerSingleEventOf().

private func checkUser (imageName:String, _ completionHandler: @escaping(Bool) -> Void)
  {
    let userExists = FIRStorage.storage().reference().child("profile_images")
    userExists.observeSingleEvent(of: .value, with:{(snapshot) in
      if snapshot.hasChild(imageName){
        print ("Image already exists")
        completionHandler(false)
      }
      else
      {
      print ("Image does not exist")
      print ("store the image")
      }
    })
  }

`

viggy28
  • 760
  • 1
  • 10
  • 21
  • Thanks - makes sense. But I am still getting an error "Value of type 'FIRStorageReference' has no member 'observeSingleEvent'... any thoughts on why? – user3708224 May 10 '17 at 14:02
  • @user3708224 sorry I thought it's for firebase database. Have a look at this question http://stackoverflow.com/questions/38184900/how-do-i-detect-if-a-firebase-storage-file-exists. – viggy28 May 10 '17 at 14:46