在创建新的配置文件图像URL之前检查Firebase存储

时间:2017-05-10 00:03:38

标签: swift firebase firebase-realtime-database firebase-storage image-caching

当用户登录我的应用时,我在检查Firebase存储时遇到了一些问题。当用户登录图像时,会在Firebase数据库和存储中成功创建并存储,但每次用户注销并重新登录到应用程序时,都会在Firebase存储中将profileImage文件(而不是子值url字符串)复制为新的和单独的图像文件。

我希望该应用在登录时检查firebase存储的profileImage文件,如果存在,则不要在存储中重新创建相同的图像。我理解检查Firebase图像的逻辑,如果不存在,则创建新图像。我只是在语法方面遇到了一些麻烦。提前感谢您的帮助!

// 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")
    })
}

1 个答案:

答案 0 :(得分:1)

我认为问题出在" if"条件。您正在引用该位置,但未检查该位置中的实际数据。

您可以使用.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")
      }
    })
  }

`