2017-01-27 1 views
-1

Firebase를 사용하여 Facebook에서 로그인을 구현 중입니다. 이메일에 대한 성공적인 페이스 북 인증 후 내 데이터베이스를 검색하는이 코드가 있습니다. 이 메소드가 비동기이기 때문에 사용자를 등록보기 컨트롤러로 보내지 만 발견되지 않으면 작동하지 않습니다. 누구든지 도와 주시면 감사하겠습니다. 내 코드는 다음과 같습니다.Firebase를 사용하는 Facebook 로그인 - Swift iOS

func getFacebookUserInfo() { 
    if(FBSDKAccessToken.current() != nil){ 
     let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id,name,gender,email,education"]) 
     let connection = FBSDKGraphRequestConnection() 
     connection.add(graphRequest, completionHandler: { (connection, result, error) -> Void in 
      let data = result as! [String : AnyObject] 
      let email = data["email"] as? String 

      let emailRef = FIRDatabase.database().reference().child("usernameEmailLink") 
      emailRef.queryOrderedByValue().observe(.childAdded, with: { snapshot in 
       if let snapshotValue = snapshot.value as? [String: AnyObject] { 
        for (key, value) in snapshotValue { 

         if(value as? String == email){ 
          self.stringMode = snapshotValue["mode"]! as! String 
          self.username = key 
          self.parseUserInfoFromJSON() 
          return 
         } 

        } 
       } 

      }) 


     }) 
     connection.start() 

    } 

} 

고맙습니다.

+1

질문이 약간 명확하지 않으므로 대답하기가 어렵습니다. 사용자가 Facebook 인증을 사용하여 인증하면 인증을받습니다. 그런 다음 전자 메일을 검색하는 이유는 무엇입니까? Firebase Facebook API는 Firebase 사용자를 선행으로 만듭니다. [Facebook 인증] (https://firebase.google.)의 4 ~ 5 단계를 참조하십시오. – Jay

+0

@Jay 내 응용 프로그램에 사용자가 등록되어 있어야합니다. – Reem

+0

그게 무슨 뜻인지는 분명하지 않지만 찾고자하는 답을 세웠습니다. – Jay

답변

3

Firebase에서 사용자의 등록/존재는 질문의 graphRequest 코드보다 먼저 결정되어야합니다.

가장 중요한 것은 이메일 주소는 동적이므로 사용자가 있는지 확인하는 데 사용해서는 안됩니다. 이메일 주소가 '[email protected]'인 사용자는 '[email protected]'으로 이메일을 업데이트합니다. 전자 메일을 사용하여 등록을 확인하는 경우 해당 전자 메일이 변경되면 완전히 중단 될 수 있습니다.

정적이며 고유하기 때문에 Firebase uid를 사용하십시오.

작은 코드 조각 만 있기 때문에 사용되는 정확한 시퀀스를 알 수 없습니다. 이 대답은 가능한 순서를 설명하기위한 의사 코드입니다.

'등록'은 사용자가 일종의 앱 등록 순서를 거쳤으며 Firebase에 사용자가 생성되었다는 것을 의미한다고 가정합니다.

일반적으로 실제 로그인 작업을 처리하기 위해 로그인 버튼과 대리인 메소드가 있습니다.

는 사용자가 자신의 로그인을 입력하고

func loginButton(loginButton: FBSDKLoginButton!, 
       didCompleteWithResult result: FBSDKLoginManagerLoginResult!, 
       error: NSError?) { 

중포 기지는 그 시점에서 해당 사용자에 대한 자격 증명 (아래 중포 기지 문서 인용 참조)

let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString) 

를 얻을 수 있습니다, 로그인 로그인 버튼을 탭 사용자가 Firebase 사용자 노드에 등록 (존재)하고 있는지 확인하십시오.

중포 기지 문서 처음으로, 새 사용자 계정 자격 증명-이며, 사용자 이름과 암호 생성 및 연결 이다 사용자가 로그인 한 후

에서

FIRAuth.auth()?.signIn(with: credential) { (user, error) in 
    if let error = error { //failed due to an error 
    return 
    } 

    let uid = user.uid //the firebase uid 
    let thisUserRef = userRef.child(uid) //a reference to the user node 

    //check to see if the user exists in firebase (i.e. is Registered) 
    thisUserRef.observeSingleEvent(of: .value, with: { (snapshot) in 

    //if snapshot exists 
     //then the user is already 'registered' in the user node 
     // so continue the app with a registered user 
    //if not, then need to have the user go through a registration sequence and 
    // then create the user (make them registered) in the user node 
     doRegisterUser(user) 
    }) 


func doRegisterUser(user: FIRUser) { 

    //get what you need from the user to register them 
    // and write it to the users node. This could be from additional 
    // questions or from their Facebook graph, as in the code in the 
    // question 

    //for this example, we'll just write their email address 
    let email = user.email 
    let dict = ["email": email] 

    //create a child node in the users node with a parent of uid 
    // and a child of email: their email 
    thisUserRef.setValue(node) 

    //next time the user logs in via FB authentication, their user node 
    // will be found as they are now a 'registered' user 
} 

, 또는 사용자가 로그인 한 공급자 정보를 인증 할 수 있습니다. 이 새 계정은 중포 기지 프로젝트의 일환으로 저장되고,에 관계없이 프로젝트에서 어떻게 사용자가 로그인의 을 모든 응용 프로그램에서 사용자를 식별하는 데 사용 수 있습니다.

내가 언급 한 바와 같이, 이것이 매우 의사 코드이지만 솔루션에 대한 가능한 시퀀스를 제공합니다.

+0

완벽. Facebook Base SignIn을 통해 firebase가 등록자와 로그인자로 작동하므로 사용자가 처음 로그인했는지 또는 재 방문하는 사용자인지를 알아낼 수있는 방법이 없습니다. – Annjawn

관련 문제