检查Apple登录电子邮件是否已在Firebase中注册

时间:2020-03-23 15:46:37

标签: ios swift firebase firebase-authentication sign-in-with-apple

在我的应用程序中,用户可以使用Apple登录。创建帐户可以正常工作(使用 Firebase )。但是,在用户实际登录之前,我想检查用户是否已经注册。为此,我需要电子邮件。问题是由于出现 found nil-错误,我无法正确访问电子邮件。

这是我的function,应处理检查/登录

// delegate functions
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
  if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
    guard let nonce = currentNonce else {
      fatalError("Invalid state: A login callback was received, but no login request was sent.")
    }
    guard let appleIDToken = appleIDCredential.identityToken else {
      print("Unable to fetch identity token")
      return
    }
    guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
      print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
      return
    }

    let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce)
    print("email: " + appleIDCredential.email!)
    let email = appleIDCredential.email

    Auth.auth().fetchSignInMethods(forEmail: email!) { (methods, error) in

         if error != nil {
            // show error popUp
             Utilities.showErrorPopUp(labelContent: "Fehler", description: error!.localizedDescription)
         } else {
             // no error -> check email adress

             // Email is not registered -> sign up
             if methods == nil {

                 print("signed in")
                 let usernameVC = self.storyboard?.instantiateViewController(withIdentifier: "UsernameVC") as! UserNameVC
                 usernameVC.credential = credential
                 usernameVC.signInOption = "apple"
                 self.navigationController?.pushViewController(usernameVC, animated: true)

             }
             // Email is registered -> login
             else {

                Auth.auth().signIn(with: credential, completion: { (user, error) in
                    if error != nil {
                        Utilities.showErrorPopUp(labelContent: "Fehler beim Login", description: error!.localizedDescription)
                    } else {

                        // set user status to logged-in
                        UserDefaults.standard.setIsLoggedIn(value: true)
                        UserDefaults.standard.synchronize()

                        // stop animation
                        self.logoAnimation.stop()

                        //transition to home
                        self.transitionToHome()
                    }
                })
             }
         }
    }
  }
}

就像我说过的那样,当用户已经登录时,此功能不起作用,只有在用户首次注册时,此功能才有效,否则似乎在获取电子邮件时会出现问题。

有人知道解决方法或有关如何解决此问题的知识吗?

3 个答案:

答案 0 :(得分:4)

如果您无法使用凭据访问email属性,则意味着该用户之前已经使用其AppleId登录了应用程序,因此您可以确定该用户是否已在此应用程序中注册:

        <?php
        $args = array('post_type' => 'glasseye_classes', 'posts_per_page' => 10);
        $loop = new WP_Query($args);

        while ($loop->have_posts()) : $loop->the_post();
            the_content();

            $meta_box_fields = $meta_box['fields'];

            // returns the key for the Name field for each Class
            $phone_copy_key = $meta_box_fields[0]['id'];
            $phone_copy_value = get_post_meta($post->ID, $phone_copy_key, true);

            $image_key = $meta_box_fields[2]['id'];
            $image_value = get_post_meta($post->ID, $image, true);

            $class_skill_key = $meta_box_fields[3]['id'];
            $class_skill_value = get_post_meta($post->ID, $class_skill_key, true);

            $class_length_key = $meta_box_fields[4]['id'];
            $class_length_value = get_post_meta($post->ID, $class_length_key, true);

            $class_description_key = $meta_box_fields[5]['id'];
            $class_description_value = get_post_meta($post->ID, $class_description_key, true);

            $class_theme_key = $meta_box_fields[6]['id'];
            $class_theme_value = get_post_meta($post->ID, $class_theme_key, true);

        ?>


            <h1><?php echo $phone_copy_value ?></h1>
            <div class="phone-animation">
                <img class="phone-animation-xlarge phone-five-animation-xlarge" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <img class="phone-animation-large phone-five-animation-large" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <img class="phone-animation-medium phone-five-animation-medium" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <img class="phone-animation-small phone-five-animation-small" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <div class="phone-image-container">
                    <img src="<?php echo $phone_value ?>" class="instructor-headshot" alt="<?php echo $class_instructor_value ?> Headshot">

                </div>

            </div>
    </div>

答案 1 :(得分:1)

在@Nikita的帮助下,我终于开始工作了。如建议我先检查是否可以访问email。我最后的function看起来像这样:

let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce)

    guard appleIDCredential.email != nil else {
        // User already signed in with this appleId once
        Auth.auth().signIn(with: credential, completion: { (user, error) in

            DataHandler.checkIfAppleUserExists(uid: (user?.user.uid)!) { (exists) in
                if exists { // user has firebase-profile -> login
                    if error != nil {
                        Utilities.showErrorPopUp(labelContent: "Fehler beim Login", description: error!.localizedDescription)
                    } else {

                        UserDefaults.standard.setIsLoggedIn(value: true)
                        UserDefaults.standard.synchronize()

                        self.logoAnimation.stop()

                        self.transitionToHome()
                    }
                } else { // user doesn't have firebase-profile -> create username
                    let usernameVC = self.storyboard?.instantiateViewController(withIdentifier: "UsernameVC") as! UserNameVC
                    usernameVC.credential = credential
                    usernameVC.signInOption = "appleExists"
                    self.navigationController?.pushViewController(usernameVC, animated: true)
                }
            }

        })
        return
    }

    // first time apple sign in
    let usernameVC = self.storyboard?.instantiateViewController(withIdentifier: "UsernameVC") as! UserNameVC
    usernameVC.credential = credential
    usernameVC.signInOption = "apple"
    self.navigationController?.pushViewController(usernameVC, animated: true)
  }

我还实现了辅助功能checkIfAppleUserExists,该功能检查用户是否实际上是在Firebase中创建的。如果是这样,则用户登录,否则他将进入创建Firebase-Profile的UsernameVC

答案 2 :(得分:-1)

如果要检查用户是否已经登录 您可以像这样检查它:

import FirebaseAuth

if Auth.auth().currentUser != nil {
// the user is signed in
} else {
// the user in not signed in
}