iosobjective-cfacebookparse-platformpffacebookutils

PFFacebookUtils. How to make difference between login and signup?


I'm trying to provide some very simple (as I thought) functionality into my application which uses Parse.com service. What I need is just allow users to create an account via Facebook and login them again via Facebook.

The problem is that PFFacebookUtils login methods not only login users through Facebook but also create a new PFUser. Why is it a problem for me? Well, of course. I can distinguish between signing up and in by isNew field but it doesn't really help.

Consider the following - user tries to login via Facebook (he doesn't any have PFUser yet), he loggs in, a new user is created. I see that the user is new (i.e. the user wasn't registered before) and I have to reject this login. Ok, I reject him, I say "You haven't been registered yet, go and sign up". User signs up (via the same login method) and this time the same PFUser is returned which was created when the user tried to log in. I see that the user is not new, it has already been registered and therefore I have to reject the user again, because the account already exists and it is impossible to create the same account again.

Do you understand the problem? Am I being idiotic not realizing how to deal with PFFacebookUtils account creation and logging in or it is PFFacebookUtils who provides an idiotic API? How do you people do that? How do you solve the problem that I've described. Really, it must be so simple but I can't find a good example anywhere


Solution

  • I have login and signup code in swift that checks to see if a user is new in login and signup. Here is my code:

    LOGIN

    let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        spinningActivity.label.text = "Just a Moment"
        spinningActivity.detailsLabel.text = "Logging in"
    
        if reachabilityStatus == kNOTREACHABLE {
    
            spinningActivity.hideAnimated(true)
    
            self.displayError("No Internet Connection", message: "Please connect to the internet before continuing")
    
        } else {
    
            let permissions = ["public_profile"]
    
            PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) { (user:PFUser?, error:NSError?) -> Void in
    
    
    
                if error != nil {
    
                    spinningActivity.hideAnimated(true)
    
                    self.displayError("Error", message: error!.localizedDescription)
    
                } else if let user = user {
                    if user.isNew {
    
                        spinningActivity.hideAnimated(true)
    
                        PFUser.currentUser()?.deleteInBackground()
    
                        self.displayNoticeWithTwoActions("Account Not Found", message: "This Facebook account is not in our system. You have to sign up first.", firstButtonTitle: "Sign Up",closeButtonTitle: "Ok", segue: "dontHaveAccountSegue")
    
                    } else {
    
                        spinningActivity.hideAnimated(true)
    
                        self.performSegueWithIdentifier("successfulLoginSegue", sender: self)
    
    
    
                    }
                } else {
    
                    PFUser.currentUser()?.deleteInBackground()
    
                    spinningActivity.hideAnimated(true)
    
                    self.displayError("Error", message: "Unless you tapped on 'Cancel' or 'Done', something went wrong. Please try again.")
    
                }
    
            }
    
        }
    

    SIGNUP

    I have a signup button and then a function that is implemented into the login button called "loadFacebookUserDetails"

    let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        spinningActivity.label.text = "Just a Moment"
        spinningActivity.detailsLabel.text = "Loading Details"
    
    
        if reachabilityStatus == kNOTREACHABLE {
    
            spinningActivity.hideAnimated(true)
    
           self.displayError("No Internet Connection", message: "Please connect to the internet before continuing")
    
        } else {
    
            let permissions = ["public_profile", "email"]
    
            PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) { (user:PFUser?, error:NSError?) -> Void in
    
                if let user = user {
    
                    if !user.isNew {
    
                        spinningActivity.hideAnimated(true)
    
                        PFUser.logOut()
    
    
                        self.displayNoticeWithTwoActions("Account Found", message: "This Facebook account already in our system. You have to log in first.", firstButtonTitle: "Log In", closeButtonTitle: "Cancel", segue: "haveAccountSegue")
    
    
    
                    } else if error != nil {
    
                        spinningActivity.hideAnimated(true)
    
                        self.displayError("Error", message: error!.localizedDescription)
    
    
    
                    } else if error == nil {
    
                        spinningActivity.hideAnimated(true)
    
                        self.loadFacebookUserDetails()
    
                    }
    
                }
    
           else {
    
                    spinningActivity.hideAnimated(true)
    
                    self.displayError("Something Went Wrong", message: "Unless you tapped on 'Cancel' or 'Done', something went wrong. Please try again")
    
                }
    
    
    
            }
    
    
        }
    

    func loadFacebookUserDetails() {
    
        let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        spinningActivity.mode = MBProgressHUDMode.AnnularDeterminate
        spinningActivity.label.text = "Just a Moment"
        spinningActivity.detailsLabel.text = "Loading Details"
    
        let requestPerameters = ["fields": "id, email, first_name, last_name, name"]
    
        let userDetails = FBSDKGraphRequest(graphPath: "me", parameters: requestPerameters)
    
        userDetails.startWithCompletionHandler { (connection, result, error:NSError!) -> Void in
    
            if error != nil {
    
                spinningActivity.hideAnimated(true)
    
                self.displayError("Error", message: error!.localizedDescription)
    
                PFUser.logOut()
    
            } else {
    
            let userID:String = result["id"] as! String
            let userEmail:String = result["email"] as! String
            let userFirstName:String = result["first_name"] as! String
            let userLastName:String = result["last_name"] as! String
    
    
            // Get Facebook Profile Picture
    
            let userProfile = "https://graph.facebook.com/" + userID + "/picture?type=large"
    
            let usernameLink = "https://graph.facebook.com/" + userID
    
            let username = usernameLink.stringByReplacingOccurrencesOfString("https://graph.facebook.com/", withString: "")
    
            let profilePictureUrl = NSURL(string: userProfile)
    
            let profilePictureData = NSData(contentsOfURL: profilePictureUrl!)
    
            if profilePictureData != nil {
    
                let profilePictureObject = PFFile(data: profilePictureData!)
                PFUser.currentUser()?.setObject(profilePictureObject!, forKey: "profile_picture")
    
            }
    
            PFUser.currentUser()?.setObject(userFirstName, forKey: "first_name")
            PFUser.currentUser()?.setObject(userLastName, forKey: "last_name")
            PFUser.currentUser()?.setObject(username, forKey: "facebook_link")
    
            if userEmail == userEmail {
    
                PFUser.currentUser()?.email = userEmail
    
            }
    
            PFUser.currentUser()?.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
    
                if error != nil {
    
                    spinningActivity.hideAnimated(true)
    
                    self.displayError("Error", message: error!.localizedDescription)
    
                    PFUser.logOut()
    
                } else if success == true {
    
                    if !userID.isEmpty {
    
                        spinningActivity.hideAnimated(true)
    
                    NSUserDefaults.standardUserDefaults().setObject("authData", forKey: "facebookAuth")
    
                        NSUserDefaults.standardUserDefaults().synchronize()
    
                        self.performSegueWithIdentifier("facebookUserDetailsSegue", sender: self)
    
    
    
                    }
    
                } else {
    
                    spinningActivity.hideAnimated(true)
    
                    self.displayError("Something Went Wrong", message: "Please try again")
    
                    PFUser.logOut()
    
                }
    
            })
    
        }
    
    }
    
    }
    

    If you have trouble with the conversion to objective c, I bet you can find YouTube videos on how to do this.