backendless.userService.loginWithFacebookSDK with swift

Hi Anatolii.

AP-ID:

2A0C7717-B5AC-0B96-FF64-5DD2DD3E8200

Here is my Class for Android


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.BackendlessUser;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;


/**
 * Created by omhack on 1/22/16.
 */
public class LoginScreen extends AppCompatActivity {


    SharedPreferences sharedPrefGar;
    SharedPreferences.Editor editor;
    public static final String MyPREFERENCES = "miprefs";
    //final List<String> permissions = Arrays.asList("public_profile", "email");
    CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginscreen);


        sharedPrefGar = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        editor = sharedPrefGar.edit();

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
    }




    public void logInToFacebook(View view) {
        Backendless.UserService.loginWithFacebookSdk( LoginScreen.this, callbackManager, new AsyncCallback<BackendlessUser>()
        {
            @Override
            public void handleResponse( BackendlessUser loggedInUser )
            {
                // user logged in successfully
                System.out.println( "User has been logged in - " + loggedInUser.getObjectId() );
                editor.putString("currntUser",loggedInUser.getObjectId());
                editor.putString("userName",loggedInUser.getEmail().toString());
                editor.commit();
                startActivity(new Intent(LoginScreen.this, MainActivity.class));            }

            @Override
            public void handleFault( BackendlessFault fault )
            {
                // failed to log in
                showToast("Verifica usuario y contraseña");
            }
        } );
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        callbackManager.onActivityResult( requestCode, resultCode, data );
    }

    private void showToast(String message){
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

}

And here is my integration with SWIFT





















/* ----->>>> In my Controller  <<<<----- */













import UIKit

import FBSDKLoginKit




class UserLoginViewController: UIViewController,FBSDKLoginButtonDelegate {

    

    

    var currentUsr : GarnachaUser?

    var backendless = Backendless.sharedInstance()

    

    

    @IBOutlet var loginWithFacebook: FBSDKLoginButton!

    

    

    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {

        NSLog("User Logged Out")

    }

    

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

        

        if ((error) != nil) {

            // Process error

            let alert = UIAlertController(title: "ALERT", message:

                "Try later", preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))

            

            self.presentViewController(alert, animated: true, completion: nil)

            NSLog("Error: " + NSError.debugDescription())

        }

        else if result.isCancelled {

            // Handle cancellations

        }

        else {

            // Navigate to other view

           

        }

    }

    

    func textFieldShouldReturn(textField: UITextField) -> Bool {

        

        /*

        Dismiss keyboard with return key

        */

      

        self.view.endEditing(true)

        return false

    }

    

    override func touchesBegan(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) {

        self.view.endEditing(true)

    }

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

    

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    




}










/* ----->>>> In my AppDelegate  <<<<----- */
















import UIKit

import FBSDKCoreKit

import FBSDKLoginKit







@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    

    var window: UIWindow?

   

    

    //MARK: - Backendless variables

    let APP_ID = "2A0C7717-B5AC-0B96-FF64-5DD2DD3E8200"

    let SECRET_KEY = "380DF4E5-5157-FB72-FF69-B716DA480800"

    let VERSION_NUM = "v1"

    var backendless = Backendless.sharedInstance()

    

    //--------------------------------------

    // MARK: - UIApplicationDelegate

    //--------------------------------------

    

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

     

        //MARK: Backenless settings

        

        backendless.initApp(APP_ID, secret:SECRET_KEY, version:VERSION_NUM)

        // If you plan to use Backendless Media Service, uncomment the following line (iOS ONLY!)

        // backendless.mediaService = MediaService()

        

        

        

        return  FBSDKApplicationDelegate.sharedInstance().application(application,

            didFinishLaunchingWithOptions: launchOptions)

    }

    

    //--------------------------------------

    // MARK: Push Notifications

    //--------------------------------------

    

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

        

    }

    

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {

        if error.code == 3010 {

            print("Push notifications are not supported in the iOS Simulator.\n")

        } else {

            print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", error)

        }

    }

    

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

        

    }

       //--------------------------------------

    // MARK: Facebook SDK Integration

    //--------------------------------------

   

    func application(application: UIApplication, openURL url: NSURL,

        sourceApplication: String?,

        annotation: AnyObject?) -> Bool {

            

            

            let result =  FBSDKApplicationDelegate.sharedInstance().application(

                application,

                openURL: url,

                sourceApplication: sourceApplication,

                annotation: annotation)

            

            if result {

                

                let token = FBSDKAccessToken.currentAccessToken()

                let fieldsMapping = [

                    "id" : "facebookId",

                    "name" : "name",

                    "birthday": "birthday",

                    "first_name": "fb_first_name",

                    "last_name" : "fb_last_name",

                    "gender": "gender",

                    "email": "email"

                ]

                

                backendless.userService.loginWithFacebookSDK(

                    token,

                    fieldsMapping: fieldsMapping,

                    response: { (var registeredUser : AnyObject! ) -> () in

                        

                        print("User has been logged in (ASYNC): \(registeredUser)")

                        

                        

                    },

                    error: { (var fault : Fault!) -> () in

                        print("Server reported an error: \(fault)")

                        

                    }

                )

            }

            

            return result

            

    }

    

    func applicationDidBecomeActive(application: UIApplication) {

  

        FBSDKAppEvents.activateApp()

    }

    

}










I am attempting to login to application id: B1C1903C-5DE4-BED4-FFBC-8124C47A2100

with Facebook user with object Id: C0B69FE3-F55D-1A60-FFF2-91FEE8246600

The user already exists and is a Facebook user. I previously have not had trouble logging in via Facebook but now cannot login without getting the error:

“Unable to register user. User already exists.”

Austin,

there is no question that you’re getting the error. The challenge is figuring out how to reproduce it on our side. Any chance you could send screenshots of the facebook app setup (from Facebook) to support@backendless.com?

Regards,
Mark

Okay, sorry I thought that info would help you reproduce. I will send screenshots.

Unfortunately, I needed to continue development so I deleted the user and re-logged in and am no longer experiencing this issue at the moment although it would still be nice to know how it occurred.

Hi Austin,

Give me your Backendless appId & secretKey, and your Facebook AppId, which you have set in this Backendless App - I’ii investigate it.
My email: slavav@themidnightcoders.com.

Regards,
Slava

Hi all,

I am getting this error too. I am using Objective-C and It seems to have happen when I started setup for Push notifications. I added the device to the provisioning profile and ran the app in Xcode. I created a new instance of the app on the device and when logging in with FB it says: <Unable to register user. User already exists.>

Its very strange. Is there a way I can force the user to take the login?

Regards

Steve

Hi Steve,

The last release of Backendless (3.0.8) has the fix in this part of UserService.
Remove this FB user from the table at dashboard of your Backendless app, and try again.

Regards,
Slava

Morning. Ok awesome. I upgraded this morning. Thanks for the update.

Did you try to remove FB user? Was it be helpful?

Hello,

I am trying to login using FB SDK with this method which is given in documentation

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool{

    let result = FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)

    

    if result {

        

        let token = FBSDKAccessToken.currentAccessToken()

        let fieldsMapping = [

            "id" : "facebookId",

            "name" : "name",

            "birthday": "birthday",

            "first_name": "fb_first_name",

            "last_name" : "fb_last_name",

            "gender": "gender",

            "email": "email"

        ]

        

        backendless.userService.loginWithFacebookSDK(

            token,

            fieldsMapping: fieldsMapping,

            response: { (user: BackendlessUser!) -> Void in

                print("user: \(user)")

            },

            error: { (fault: Fault!) -> Void in

                print("Server reported an error: \(fault)")

        })

    }

    

    return result

}

and i am getting this error:

FAULT = ‘3012’ [Unable to register user. Property ‘email’ is required] <Unable to register user. Property ‘email’ is required>

which is probably because with this method facebook just asked for my public profile and not email or any other fields.

How can use permissions with this method? Please suggest if there is any other way for logging in with FB SDK.

Thank You

How to integrate FB login with the following code? It’s continuously giving errors “String.Type aka unwrapped… to type String!”

let backendless = Backendless.sharedInstance() // Use the following code to retrieve parameters from // AccessToken. The AccessToken class is available in // Facebook Swift SDK let token = AccessToken.current!let userId : String = token.userIdlet tokenString : String = token.authenticationTokenlet expirationDate : Date = token.expirationDatelet fieldsMapping = NSDictionary(dictionary:[“email” : “email”]) // synchronous methodlet backendless = Backendless.sharedInstance()!func backendless.userService.login(withFacebookSDK: String!, tokenString: String!, expirationDate:Date!, fieldsMapping: Any!) -> BackendlessUser // asynchronous methodlet backendless = Backendless.sharedInstance()!func backendless.userService.login(withFacebookSDK: String!, tokenString: String!, expirationDate:Date!, fieldsMapping:Any!, response: ((BackendlessUser?) -> Void)!, error: ((Fault?) -> Void)!) -> Void

Kindly help me in resolving this error while authenticating Facebook users with Backendless!