void LoginManagerLoginHandler(LoginManagerLoginResult result, NSError error)
        {
            if (result.IsCancelled)
            {
                _completionSource?.TrySetResult(new LoginResult {
                    LoginState = LoginState.Canceled
                });
            }
            else if (error != null)
            {
                _completionSource?.TrySetResult(new LoginResult {
                    LoginState = LoginState.Failed, ErrorString = error.LocalizedDescription
                });
            }
            else
            {
                _loginResult = new LoginResult
                {
                    Token    = result.Token.TokenString,
                    UserId   = result.Token.UserID,
                    ExpireAt = result.Token.ExpirationDate.ToDateTime()
                };

                var request = new GraphRequest(@"me", new NSDictionary(@"fields", @"email, first_name, last_name, picture.width(1000).height(1000)"));
                request.Start(GetEmailRequestHandler);
            }
        }
        public Task <FacebookUserInfo> GetUserInfo()
        {
            var keys   = new object [] { "fields" };
            var values = new object [] { "id,first_name,last_name,email" };

            string version    = new GraphRequest("/me", null).Version;
            string httpMethod = new GraphRequest("/me", null).HTTPMethod;

            GraphRequest graphRequest = new GraphRequest("/me", NSDictionary.FromObjectsAndKeys(values, keys), AccessToken.CurrentAccessToken.TokenString, version, httpMethod);

            var tcs = new TaskCompletionSource <FacebookUserInfo>();

            graphRequest.Start((GraphRequestConnection connection, NSObject result, NSError error) =>
            {
                if (error == null)
                {
                    tcs.TrySetResult(FacebookUserInfo.CreateFrom(((NSDictionary)result).Select(v => new KeyValuePair <string, string>(v.Key.ToString(), v.Value.ToString())).ToDictionary(v => v.Key, v => v.Value)));
                }
                else
                {
                    tcs.SetException(new NSErrorException(error));
                }
            });

            return(tcs.Task);
        }
Example #3
0
        void LoginManagerLoginHandler(LoginManagerLoginResult result, NSError error)
        {
            if (result.IsCancelled)
            {
                completionSource.TrySetResult(new FacebookLoginResult {
                    LoginState = FacebookLoginState.Canceled
                });
            }
            else if (error != null)
            {
                completionSource.TrySetResult(new FacebookLoginResult {
                    LoginState = FacebookLoginState.Failed, ErrorString = error.LocalizedDescription
                });
            }
            else
            {
                loginResult = new FacebookLoginResult
                {
                    Token    = result.Token.TokenString,
                    UserId   = result.Token.UserID,
                    ExpireAt = result.Token.ExpirationDate.ToDateTime()
                };

                var request = new GraphRequest(@"me", new NSDictionary(@"fields", @"email"));
                request.Start(GetEmailRequestHandler);
            }
        }
Example #4
0
        public async Task <Dictionary <string, string> > QueryFacebookApi(string query)
        {
            var result = new Dictionary <string, string>();

            var request = new GraphRequest(query, null);

            var graphTask = new TaskCompletionSource <NSObject>();

            try
            {
                request.Start((connection, graphApiResult, error) => { graphTask.TrySetResult(graphApiResult); });
            }
            catch (Exception e)
            {
                graphTask.SetException(e);
            }

            var nsObject = (NSDictionary)await graphTask.Task;

            foreach (var key in nsObject.Keys)
            {
                result[key.ToString()] = nsObject[key].ToString();
            }

            return(result);
        }
Example #5
0
        void LoginManagerLoginHandler(LoginManagerLoginResult result, NSError error)
        {
            if (result.IsCancelled)
            {
                _completionSource.TrySetResult(new LoginResult {
                    LoginState = LoginState.Canceled
                });
            }
            else if (error != null)
            {
                _completionSource.TrySetResult(new LoginResult {
                    LoginState = LoginState.Failed, ErrorString = error.LocalizedDescription
                });
            }
            else
            {
                _loginResult = new LoginResult
                {
                    Token    = result.Token.TokenString,
                    UserId   = result.Token.UserId,
                    ExpireAt = result.Token.ExpirationDate.ToDateTime()
                };
            }

            UIApplication.SharedApplication.OpenUrl(new NSUrl("http://www.facebook.com/looneyinvaders"));

            var request = new GraphRequest(@"101000795058301", new NSDictionary(@"fields", @"fan_count"));

            request.Start(GetLikesRequestHandler);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            // If was send true to Profile.EnableUpdatesOnAccessTokenChange method
            // this notification will be called after the user is logged in and
            // after the AccessToken is gotten
            Profile.Notifications.ObserveDidChange((sender, e) => {
                if (e.NewProfile == null)
                {
                    return;
                }

                nameLabel.Text = e.NewProfile.Name;
            });

            // Set the Read and Publish permissions you want to get
            loginButton = new LoginButton(new CGRect(80, 20, 220, 46))
            {
                Permissions = readPermissions.ToArray(),
                Delegate    = this
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView(new CGRect(80, 100, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel(new CGRect(80, 340, 220, 21))
            {
                TextAlignment   = UITextAlignment.Center,
                BackgroundColor = UIColor.Clear
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null)
            {
                var request = new GraphRequest("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null)
                    {
                        new UIAlertView("Error...", error.Description, null, "Ok", null).Show();
                        return;
                    }

                    // Get your profile name
                    var userInfo   = result as NSDictionary;
                    nameLabel.Text = userInfo ["name"].ToString();
                });
            }

            // Add views to main view
            View.AddSubview(loginButton);
            View.AddSubview(pictureView);
            View.AddSubview(nameLabel);
        }
        public Task <SocialData> GetPersonData()
        {
            _facebookTask = new TaskCompletionSource <SocialData>();
            CancellationToken canellationToken = new CancellationToken(true);

            manager.LogInWithReadPermissions(readPermissions.ToArray(), (res, e) =>
            {
                if (e != null)
                {
                    Mvx.Trace($"FacebookLoginButton error {e}");
                    _facebookTask.TrySetResult(null);
                    return;
                }

                try
                {
                    if (AccessToken.CurrentAccessToken == null)
                    {
                        Mvx.Trace($"Empty token");
                        manager.LogOut();
                        _facebookTask.TrySetCanceled(canellationToken);
                        //GetPersonData();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message, ex.StackTrace);
                }

                GraphRequest request = new GraphRequest("/me", new NSDictionary("fields", "name,picture,email"), AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start(new GraphRequestHandler((connection, result, error) =>
                {
                    FacebookAccountResult acct = new FacebookAccountResult()
                    {
                        Id    = result.ValueForKey(new NSString("id")).ToString(),
                        Name  = result.ValueForKey(new NSString("name")).ToString(),
                        Email = result.ValueForKey(new NSString("email")).ToString()
                    };

                    if (acct != null)
                    {
                        Mvx.Trace($"Profile: {acct.Name}, {acct.Email}, {acct.PhotoUrl}");
                        _facebookTask.TrySetResult(new SocialData()
                        {
                            Email     = acct.Email,
                            FirstName = acct.Name,
                            Photo     = acct.PhotoUrl,
                            Source    = AuthorizationType.Facebook
                        });
                    }
                }));
            });
            return(_facebookTask.Task);
        }
Example #8
0
        public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
        {
            base.PrepareForSegue(segue, sender);
            if (user.name == "")
            {
                var request = new GraphRequest("me", null);
                request.Start((connection, result, error) =>
                {
                    var userInfo = result as Foundation.NSDictionary;
                    user.name    = userInfo["name"].ToString();
                    DataStorage.Instance.UpdateUser(user);
                });
            }
            var returningUser = segue.DestinationViewController as NewTripController;

            returningUser.user = user;
        }
        public async Task <FbLoginResult> SignIn()
        {
            var tcs = new TaskCompletionSource <FbLoginResult>();

            manager = new LoginManager();
            manager.Init();
            var result = await manager.LogInWithReadPermissionsAsync(new string[] { "email", "public_profile" }, GetController());

            if (!result.IsCancelled)
            {
                try
                {
                    var request = new GraphRequest("/me?fields=id,name,email", null, result.Token.TokenString, null, "GET");
                    request.Start((connection, res, error) =>
                    {
                        var userInfo = res as NSDictionary;
                        var id       = userInfo["id"].ToString();
                        var name     = userInfo["name"].ToString();
                        var email    = userInfo["email"].ToString();
                        tcs.SetResult(new FbLoginResult
                        {
                            AccessToken = result.Token.TokenString.ToString(),
                            UserId      = id,
                            Name        = name,
                            Email       = email,
                            Status      = FBStatus.Success
                        });
                    });
                    isLoggedIn = true;
                }
                catch { }
            }
            else if (result.IsCancelled)
            {
                isLoggedIn = false;
                tcs.SetResult(new FbLoginResult()
                {
                    Status = FBStatus.Cancelled, Message = "Cancelled"
                });
            }

            return(await tcs.Task);
        }
        private void OnLoginHandler(LoginManagerLoginResult result, NSError error)
        {
            if (error != null || result == null || result.IsCancelled)
            {
                if (result != null && result.IsCancelled)
                {
                    OnLoginError?.Invoke(new Exception("Login Canceled."));
                }

                if (error != null)
                {
                    OnLoginError?.Invoke(new Exception(error.LocalizedDescription));
                }
            }
            else
            {
                var request = new GraphRequest("me", new NSDictionary("fields", "id, first_name, email, last_name, picture.width(500).height(500)"));
                request.Start(OnRequestHandler);
            }
        }
Example #11
0
 private void LoginManagerLoginHandler(LoginManagerLoginResult result, NSError error)
 {
     if (result.IsCancelled)
     {
         _completionSource.TrySetResult(new LoginResult(LoginState.Canceled, null));
     }
     else if (error != null)
     {
         _completionSource.TrySetResult(new LoginResult
                                        (
                                            LoginState.Failed,
                                            null,
                                            error.LocalizedDescription
                                        ));
     }
     else
     {
         var request = new GraphRequest(@"me", null);
         request.Start(GetDetailsRequestHandler);
     }
 }
Example #12
0
        private void ProcessFBInfo()
        {
            var request = new GraphRequest("/me?fields=email,picture,birthday,gender,link", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");

            request.Start((connection, result, error) => {
                if (error != null)
                {
                    new UIAlertView("Error...", error.Description, null, "Ok", null).Show();
                    return;
                }

                loginView.Enabled       = false;
                loginView.Alpha         = 0.5f;
                var userInfo            = result as NSDictionary;
                viewModel.FacebookEmail = (userInfo["email"] != null) ? userInfo["email"].ToString() : "";

                if (userInfo["birthday"] != null)
                {
                    viewModel.FacebookBirthday = userInfo["birthday"].ToString();
                }

                if (userInfo["gender"] != null)
                {
                    viewModel.FacebookGender = userInfo["gender"].ToString();
                }

                if (userInfo["link"] != null)
                {
                    viewModel.FacebookLink = userInfo["link"].ToString();
                }

                var nsImageURL          = Profile.CurrentProfile.ImageUrl(ProfilePictureMode.Normal, new CGSize(220, 220));
                viewModel.FacebookPhoto = nsImageURL.AbsoluteString;
                viewModel.SaveFacebookProfileAsync();
            });
        }
Example #13
0
        protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null || this.Element == null)
            {
                return;
            }

            loginButton = new LoginButton(new CGRect(48, 0, 218, 46))
            {
                LoginBehavior   = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };

            var facebookLoginButtonText = new NSAttributedString("Entrar com Facebook",
                                                                 new UIStringAttributes()
            {
                ForegroundColor = UIColor.White
            });

            loginButton.SetAttributedTitle(facebookLoginButtonText, UIControlState.Normal);

            loginButton.Completed += (sender, args) =>
            {
                FacebookButton    facebookButton = (FacebookButton)e.NewElement;
                FacebookEventArgs fbArgs         = new FacebookEventArgs();


                if (args.Result.Token != null)
                {
                    fbArgs.UserId          = args.Result.Token.UserID;
                    fbArgs.AccessToken     = args.Result.Token.TokenString;
                    fbArgs.TokenExpiration = args.Result.Token.ExpirationDate.ToDateTime();

                    var request = new GraphRequest("/" + args.Result.Token.UserID, new NSDictionary("fields", "first_name,last_name,email,birthday,picture"), AccessToken.CurrentAccessToken.TokenString, null, "GET");
                    request.Start((connection, result, error) =>
                    {
                        var userInfo   = result as NSDictionary;
                        nameLabel.Text = userInfo["first_name"].ToString();

                        ((App)App.Current).settings.AccessToken = fbArgs.AccessToken;

                        try
                        {
                            //((App)App.Current).settings.BirthDay = DateTime.Parse(userInfo["birthday"].ToString() + " 00:00:00");
                            ((App)App.Current).settings.Email = userInfo["email"].ToString();
                        }
                        catch (Exception erro)
                        {
                            Console.WriteLine(erro.Message);
                        }

                        ((App)App.Current).settings.ExpirinDate = fbArgs.TokenExpiration;
                        ((App)App.Current).settings.Name        = userInfo["first_name"].ToString() + " " + userInfo["last_name"].ToString();
                        ((App)App.Current).settings.Imagem      = userInfo["picture"].ToString();

                        var picture = userInfo["picture"] as NSDictionary;
                        picture     = picture["data"] as NSDictionary;

                        ((App)App.Current).settings.Imagem = picture["url"].ToString();
                        ((App)App.Current).settingsViewModel.Gravar();
                        ((App)App.Current).NavigateToHome();
                    });
                }


                facebookButton.Login(facebookButton, fbArgs);
                // The user image profile is set automatically once is logged in

                //pictureView = new ProfilePictureView(new CGRect(80, -500, 220, 220));
                //this.AddSubview(pictureView);

                nameLabel = new UILabel(new RectangleF(80, -200, 280, 280))
                {
                    TextAlignment   = UITextAlignment.Center,
                    BackgroundColor = UIColor.Clear
                };
                this.AddSubview(nameLabel);
            };

            SetNativeControl(loginButton);
        }
        private void FinalizeLogin()
        {
            if (AccessToken.CurrentAccessToken != null) {
                var request = new GraphRequest ("/me?fields=name,id,birthday,first_name,gender,last_name,interested_in,location", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;

                    LettuceServer.Instance.FacebookLogin (userInfo["id"].ToString(), AccessToken.CurrentAccessToken.TokenString, (theUser) => {
                        InvokeOnMainThread(() => {
                            LoginView.Hidden = true;
                            LightBox.Hidden = true;
                            RefreshButtonCounts();
                            });
                        });
                });
            }
        }
        private void InitFacebookLogin()
        {
            LoginView.Hidden = false;
            Profile.Notifications.ObserveDidChange ((sender, e) => {

                if (e.NewProfile == null)
                    return;

                LoginView.Hidden = true;
                LightBox.Hidden = true;
                nameLabel.Text = e.NewProfile.Name;
            });
            CGRect viewBounds = LoginView.Bounds;

            // Set the Read and Publish permissions you want to get
            nfloat leftEdge = (viewBounds.Width - 220) /2;
            loginButton = new LoginButton (new CGRect (leftEdge, 60, 220, 46)) {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray ()
            };

            // Handle actions once the user is logged in
            loginButton.Completed += (sender, e) => {
                if (e.Error != null) {
                    // Handle if there was an error
                }

                if (e.Result.IsCancelled) {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
                FinalizeLogin();
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) => {
                // Handle your logout
                nameLabel.Text = "";
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView (new CGRect (leftEdge, 140, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel (new CGRect (20, 360, viewBounds.Width - 40, 21)) {
                TextAlignment = UITextAlignment.Center,
                BackgroundColor = UIColor.Clear
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null) {
                var request = new GraphRequest ("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;
                    nameLabel.Text = userInfo ["name"].ToString ();
                    var controller = AppDelegate.ProfileController;
                    this.NavigationController.PresentViewController(controller, true, null);

                });
            }

            // Add views to main view
            LoginView.AddSubview (loginButton);
            LoginView.AddSubview (pictureView);
            LoginView.AddSubview (nameLabel);
        }
        public void Login(Action <FBUser, string> onLoginComplete)
        {
            _onLoginComplete = onLoginComplete;

            var viewController = GetPresetedViewController();

            var tcs = new TaskCompletionSource <FBUser>();

            var loginManager = new LoginManager();

            loginManager.LogOut();
            loginManager.LoginBehavior = LoginBehavior.SystemAccount;
            loginManager.LogInWithReadPermissions(new[] { "public_profile", "email" }, viewController,
                                                  (result, error) =>
            {
                if (error != null || result == null || result.IsCancelled)
                {
                    if (error != null)
                    {
                        _onLoginComplete?.Invoke(null, error.LocalizedDescription);
                    }
                    if (result.IsCancelled)
                    {
                        _onLoginComplete?.Invoke(null, "user cancelled.");
                    }
                }
                else
                {
                    var request = new GraphRequest("me",
                                                   new NSDictionary("fields",
                                                                    "id, first_name, email, last_name, picture.width(1000).height(1000)"));

                    request.Start(
                        (conn, fetched, fetchErr) =>
                    {
                        if (fetchErr != null || fetched == null)
                        {
                            Debug.WriteLine(fetchErr.LocalizedDescription);
                            tcs.TrySetResult(null);
                        }
                        else
                        {
                            var id         = string.Empty;
                            var first_name = string.Empty;
                            var email      = string.Empty;
                            var last_name  = string.Empty;
                            var url        = string.Empty;

                            try
                            {
                                id = fetched.ValueForKey(new NSString("id"))?.ToString();
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.Message);
                            }

                            try
                            {
                                first_name = fetched.ValueForKey(new NSString("first_name"))?.ToString();
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.Message);
                            }

                            try
                            {
                                last_name = fetched.ValueForKey(new NSString("last_name"))?.ToString();
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.Message);
                            }

                            try
                            {
                                email = fetched.ValueForKey(new NSString("email"))?.ToString();
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.Message);
                            }


                            try
                            {
                                url = ((fetched.ValueForKey(new NSString("picture")) as NSDictionary)?.ValueForKey(new NSString("data")) as NSDictionary)?.ValueForKey(new NSString("url")).ToString();
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.Message);
                            }
                            var fbUser = new FBUser()
                            {
                                Id        = id,
                                Email     = email,
                                FirstName = first_name,
                                LastName  = last_name,
                                PicUrl    = url,
                                Token     = result.Token.TokenString
                            };
                            tcs.TrySetResult(fbUser);
                            _onLoginComplete?.Invoke(fbUser, string.Empty);
                        }
                    }
                        );
                }
            });
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            loginFacebookButton.TouchUpInside += delegate {
                Console.WriteLine("presing facebook link");

                loginView.SendActionForControlEvents(UIControlEvent.TouchUpInside);
            };



            get_helplbl.TextColor = UIColor.FromRGB(112, 112, 112);

            back_button.SetTitleColor(UIColor.FromRGB(75, 171, 229), UIControlState.Normal);

            loginButton.BackgroundColor = UIColor.FromRGB(75, 171, 229);



            signup_lbl.TextColor = UIColor.FromRGB(112, 112, 112);

            passwordText.SecureTextEntry = true;

            Profile.CurrentProfile = null;

            AccessToken.CurrentAccessToken = null;

            NSHttpCookieStorage storage = NSHttpCookieStorage.SharedStorage;

            foreach (NSHttpCookie cookie in storage.Cookies)
            {
                if (cookie.Domain == "facebook.com")
                {
                    storage.DeleteCookie(cookie);
                }
            }


            NSUrlCache.SharedCache.RemoveAllCachedResponses();
            var cookies = NSHttpCookieStorage.SharedStorage.Cookies;

            foreach (var c in cookies)
            {
                NSHttpCookieStorage.SharedStorage.DeleteCookie(c);
            }

            var websiteDataTypes = new NSSet <NSString>(new[]
            {
                //Choose which ones you want to remove
                WKWebsiteDataType.Cookies,
                WKWebsiteDataType.DiskCache,
                WKWebsiteDataType.IndexedDBDatabases,
                WKWebsiteDataType.LocalStorage,
                WKWebsiteDataType.MemoryCache,
                WKWebsiteDataType.OfflineWebApplicationCache,
                WKWebsiteDataType.SessionStorage,
                WKWebsiteDataType.WebSQLDatabases
            });

            WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(websiteDataTypes, (NSArray records) =>
            {
                for (nuint i = 0; i < records.Count; i++)
                {
                    var record = records.GetItem <WKWebsiteDataRecord>(i);

                    WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(record.DataTypes,
                                                                          new[] { record }, () => { Console.Write($"deleted: {record.DisplayName}"); });
                }
            });

            NavigationController.NavigationBarHidden = true;

            this.View.BringSubviewToFront(passwordText);

            this.View.BringSubviewToFront(emailText);

            this.View.BringSubviewToFront(back_button);

            var screenTap = new UITapGestureRecognizer(() =>
            {
                emailText.ResignFirstResponder();
                passwordText.ResignFirstResponder();
            });

            var show_signup = new UITapGestureRecognizer(() =>
            {
                ViewModel.ShowSignUp();
            });

            this.View.AddGestureRecognizer(screenTap);

            this.signup_lbl.AddGestureRecognizer(show_signup);

            this.signup_lbl.UserInteractionEnabled = true;

            back_button.TouchUpInside += (sender, e) => {
                ViewModel.BackIntroduction();
            };

            ViewModel.ForPropertyChange(x => x.ErrorMessage, y =>
            {
                //Debug.WriteLine("PORPOISE LOGO CHANGED");

                var okAlertController = UIAlertController.Create("Error message", ViewModel.ErrorMessage, UIAlertControllerStyle.Alert);

                //Add Action
                okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                // Present Alert
                PresentViewController(okAlertController, true, null);
            });



            loginButton.TouchUpInside += (sender, e) => {
                if (!string.IsNullOrEmpty(emailText.Text) && !string.IsNullOrEmpty(passwordText.Text))
                {
                    ViewModel.email = emailText.Text;

                    ViewModel.password = passwordText.Text;

                    ViewModel.Login();
                }

                else if (string.IsNullOrEmpty(emailText.Text))
                {
                    var okAlertController = UIAlertController.Create("Error message", "Please enter email", UIAlertControllerStyle.Alert);

                    //Add Action
                    okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    // Present Alert
                    PresentViewController(okAlertController, true, null);
                }

                else if (string.IsNullOrEmpty(passwordText.Text))
                {
                    var okAlertController = UIAlertController.Create("Error message", "Please enter password", UIAlertControllerStyle.Alert);

                    //Add Action
                    okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    // Present Alert
                    PresentViewController(okAlertController, true, null);
                }

                //UsingOauth();
            };



            Profile.Notifications.ObserveDidChange((sender, e) => {
                if (e.NewProfile == null)
                {
                    return;
                }
                if (AccessToken.CurrentAccessToken != null)
                {
                    var request = new GraphRequest("/me?fields=first_name,last_name,name,email,picture,birthday,gender", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                    request.Start((connection, result, error) =>
                    {
                        // Handle if something went wrong with the request
                        if (error != null)
                        {
                            //showAlert("Error", error.Description);
                            return;
                        }

                        //fbReponseFromSDK facebookSDKLoginItem = new fbReponseFromSDK();
                        // Get your profile name
                        var userInfo = result as NSDictionary;
                        if (userInfo["id"] != null)
                        {
                            ViewModel.provider_id = userInfo["id"].ToString();

                            ViewModel.user_login_provider.user_provider_id = userInfo["id"].ToString();

                            Console.WriteLine("id is: " + userInfo["id"].ToString());
                        }
                        if (userInfo["name"] != null)
                        {
                            ViewModel.user_login_provider.user_provider_name = userInfo["name"].ToString();

                            Console.WriteLine("name is: " + userInfo["name"].ToString());
                        }

                        if (userInfo["first_name"] != null)
                        {
                            ViewModel.first_name = userInfo["first_name"].ToString();

                            Console.WriteLine("first_name is: " + userInfo["first_name"].ToString());
                        }

                        if (userInfo["last_name"] != null)
                        {
                            ViewModel.last_name = userInfo["last_name"].ToString();

                            Console.WriteLine("last_name is: " + userInfo["last_name"].ToString());
                        }

                        if (userInfo["email"] != null)
                        {
                            ViewModel.email = userInfo["email"].ToString();

                            Console.WriteLine("email is: " + userInfo["email"].ToString());
                        }

                        if (userInfo["picture"] != null)
                        {
                            Console.WriteLine("profile image is: " + userInfo["picture"].ToString());
                        }

                        if (userInfo["birthday"] != null)
                        {
                            var formatted        = DateTime.Parse(userInfo["birthday"].ToString());
                            ViewModel.birth_date = formatted.ToString("yyyy-MM-dd");
                            Console.WriteLine("birthday is: " + userInfo["birthday"].ToString());
                        }

                        if (userInfo["gender"] != null)
                        {
                            if (userInfo["gender"].Equals("male"))
                            {
                                ViewModel.gender = "MALE";
                            }
                            else if (userInfo["gender"].Equals("female"))
                            {
                                ViewModel.gender = "FEMALE";
                            }
                            Console.WriteLine("gender is: " + userInfo["gender"].ToString());
                        }
                        //(Success) Do what you want next :
                        //doneFacbookLogin();

                        //loginView.LoggedOut();

                        ViewModel.user_login_provider.provider = "FACEBOOK";

                        ViewModel.EmailVerification();
                    });
                }

                nameLabel.Text = e.NewProfile.Name;
            });

            // Set the Read and Publish permissions you want to get
            loginView = new LoginButton(new CGRect(0, 0, loginFacebookButton.Frame.Width, loginFacebookButton.Frame.Height))
            {
                //LoginBehavior = LoginBehavior.,
                Permissions = readPermissions.ToArray()
            };



            var attributes = new UIStringAttributes
            {
                BackgroundColor = UIColor.FromRGB(75, 171, 229),

                ForegroundColor = UIColor.White,
                Font            = UIFont.FromName("System Semibold", 17f)
            };
            var titleText = new NSAttributedString("Log In With Facebook", attributes);

            loginView.SetAttributedTitle(titleText, UIControlState.Normal);

            loginView.SetBackgroundImage(null, UIControlState.Normal);

            loginView.BackgroundColor = UIColor.FromRGB(75, 171, 229);
            // Handle actions once the user is logged in
            loginView.Completed += (sender, e) => {
                if (e.Error != null)
                {
                    // Handle if there was an error
                }

                if (e.Result.IsCancelled)
                {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
            };

            // Handle actions once the user is logged out
            loginView.LoggedOut += (sender, e) => {
                Profile.CurrentProfile = null;
                // Handle your logout
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView(new CGRect(50, 50, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel(new RectangleF(20, 319, 280, 21))
            {
                TextAlignment   = UITextAlignment.Center,
                BackgroundColor = UIColor.Clear
            };

            // Add views to main view

            Console.WriteLine();

            loginFacebookButton.BackgroundColor = UIColor.FromRGB(75, 171, 229);

            //loginFacebookButton.AddSubview(loginView);
        }
        //        public override void ViewDidLoad ()
        //        {
        //            
        //        }
        public override void ViewDidLoad()
        {
            Profile.Notifications.ObserveDidChange ((sender, e) => {

                if (e.NewProfile == null)
                    return;

                nameLabel.Text = e.NewProfile.Name;
            });

            // Set the Read and Publish permissions you want to get
            loginButton = new LoginButton (new CGRect (100, 100, 220, 46)) {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray ()
            };

            // Handle actions once the user is logged in
            loginButton.Completed += (sender, e) => {
                if (e.Error != null) {
                    // Handle if there was an error
                }

                if (e.Result.IsCancelled) {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) => {
                // Handle your logout
                nameLabel.Text = "";
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView (new CGRect (100, 160, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel (new CGRect (100, 400, 280, 21)) {
                TextAlignment = UITextAlignment.Left,
                BackgroundColor = UIColor.Clear
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null) {
                var request = new GraphRequest ("/me/friends", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;
                    var friendlist = userInfo["data"];
                    var summary = userInfo["summary"];
                });
            }

            // Add views to main view
            View.AddSubview (loginButton);
            View.AddSubview (pictureView);
            View.AddSubview (nameLabel);
        }
Example #19
0
		private Task<FacebookUser> getUserData(Facebook.CoreKit.AccessToken token)
		{
			var fbUser = new FacebookUser()
				{
					Token = token.TokenString,
					ExpiryDate = token.ExpirationDate.ToDateTime()
				};

			var completion = new TaskCompletionSource<FacebookUser>();

			var request = new GraphRequest("me", NSDictionary.FromObjectAndKey(new NSString("id, first_name, last_name, email, location"), new NSString("fields")), "GET");
			request.Start((connection, result, error) =>
				{					
					if(error != null)
					{
						Mvx.Trace(MvxTraceLevel.Error, error.ToString());
					}
					else
					{
						
						var data = NSJsonSerialization.Serialize(result as NSDictionary, 0, out error);
						if(error != null)
						{
							Mvx.Trace(MvxTraceLevel.Error, error.ToString());
						}
						else
						{
							var json = new NSString(data, NSStringEncoding.UTF8).ToString();
							fbUser.User = JsonConvert.DeserializeObject<User>(json);
							fbUser.User.ProfilePictureUrl =  string.Format("https://graph.facebook.com/{0}/picture?width={1}&height={1}", fbUser.User.ID, Constants.FBProfilePicSize);
						}
						completion.TrySetResult(fbUser);	
					}

				});
			return completion.Task;
		}
Example #20
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            link_profile.Frame = new CGRect(this.View.Frame.Width / 2 - 150, 206, 300, 60);

            link_profile.TouchUpInside += delegate {
                Console.WriteLine("presing facebook link");

                loginView.SendActionForControlEvents(UIControlEvent.TouchUpInside);
            };

            back_button.TouchUpInside += delegate
            {
                ViewModel.ShowBubbleBoard();
            };

            addBubble_button.TouchUpInside += delegate
            {
                {
                    ViewModel.description = txtfield.Text;

                    ViewModel.AddBubble();
                }
            };

            var screenTap = new UITapGestureRecognizer(() =>
            {
                txtfield.ResignFirstResponder();
            });

            this.View.AddGestureRecognizer(screenTap);

            txtfield.ShouldReturn = (textField) =>
            {
                txtfield.ResignFirstResponder();
                return(true);
            };

            addBubble_button.BackgroundColor = UIColor.FromRGB(75, 171, 229);

            Profile.Notifications.ObserveDidChange((sender, e) => {
                if (e.NewProfile == null)
                {
                    return;
                }
                if (AccessToken.CurrentAccessToken != null)
                {
                    var request = new GraphRequest("/me?fields=first_name,last_name,name,email,picture,birthday,gender", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                    request.Start((connection, result, error) =>
                    {
                        // Handle if something went wrong with the request
                        if (error != null)
                        {
                            //showAlert("Error", error.Description);
                            return;
                        }

                        //fbReponseFromSDK facebookSDKLoginItem = new fbReponseFromSDK();
                        // Get your profile name
                        var userInfo = result as NSDictionary;
                        if (userInfo["id"] != null)
                        {
                            //ViewModel.provider_id = userInfo["id"].ToString();

                            //ViewModel.user_login_provider.user_provider_id = userInfo["id"].ToString();

                            Console.WriteLine("id is: " + userInfo["id"].ToString());
                        }
                        if (userInfo["name"] != null)
                        {
                            //ViewModel.user_login_provider.user_provider_name = userInfo["name"].ToString();

                            Console.WriteLine("name is: " + userInfo["name"].ToString());
                        }

                        if (userInfo["first_name"] != null)
                        {
                            //ViewModel.first_name = userInfo["first_name"].ToString();

                            Console.WriteLine("first_name is: " + userInfo["first_name"].ToString());
                        }

                        if (userInfo["last_name"] != null)
                        {
                            //ViewModel.last_name = userInfo["last_name"].ToString();

                            Console.WriteLine("last_name is: " + userInfo["last_name"].ToString());
                        }

                        if (userInfo["email"] != null)
                        {
                            //ViewModel.email = userInfo["email"].ToString();

                            Console.WriteLine("email is: " + userInfo["email"].ToString());
                        }

                        if (userInfo["picture"] != null)
                        {
                            Console.WriteLine("profile image is: " + userInfo["picture"].ToString());
                        }

                        if (userInfo["birthday"] != null)
                        {
                            var formatted = DateTime.Parse(userInfo["birthday"].ToString());
                            //ViewModel.birth_date = formatted.ToString("yyyy-MM-dd");
                            Console.WriteLine("birthday is: " + userInfo["birthday"].ToString());
                        }

                        if (userInfo["gender"] != null)
                        {
                            if (userInfo["gender"].Equals("male"))
                            {
                                //ViewModel.gender = "MALE";
                            }
                            else if (userInfo["gender"].Equals("female"))
                            {
                                //ViewModel.gender = "FEMALE";
                            }
                            Console.WriteLine("gender is: " + userInfo["gender"].ToString());
                        }
                        //(Success) Do what you want next :
                        //doneFacbookLogin();

                        //loginView.LoggedOut();

                        //ViewModel.user_login_provider.provider = "FACEBOOK";

                        //ViewModel.EmailVerification();
                    });
                }

                //nameLabel.Text = e.NewProfile.Name;
            });

            loginView = new LoginButton(new CGRect(0, 0, link_profile.Frame.Width, link_profile.Frame.Height))
            {
                LoginBehavior = LoginBehavior.Browser,
                Permissions   = readPermissions.ToArray()
            };



            var attributes = new UIStringAttributes
            {
                //BackgroundColor = UIColor.FromRGB(75, 171, 229),

                ForegroundColor = UIColor.White,
                Font            = UIFont.FromName("Helvetica-Bold", 17f)
            };
            var titleText = new NSAttributedString("Link Facebook profile", attributes);

            loginView.SetAttributedTitle(titleText, UIControlState.Normal);

            loginView.SetBackgroundImage(null, UIControlState.Normal);



            loginView.BackgroundColor = UIColor.FromRGB(75, 171, 229);
            // Handle actions once the user is logged in
            loginView.Completed += (sender, e) => {
                if (e.Error != null)
                {
                    // Handle if there was an error
                }

                if (e.Result.IsCancelled)
                {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
            };

            // Handle actions once the user is logged out
            loginView.LoggedOut += (sender, e) => {
                Profile.CurrentProfile = null;
                // Handle your logout
            };



            // The user image profile is set automatically once is logged in


            // Add views to main view

            Console.WriteLine();

            loginView.Layer.CornerRadius = 20;

            link_profile.BackgroundColor = UIColor.FromRGB(75, 171, 229);

            //link_profile.AddSubview(loginView);
        }
Example #21
0
        // Facebook Authentification
        void FacebookAuthentication()
        {
            flag = false;
            // If was send true to Profile.EnableUpdatesOnAccessTokenChange method
            // this notification will be called after the user is logged in and
            // after the AccessToken is gotten
            Profile.Notifications.ObserveDidChange((sender, e) =>
            {
                if (e.NewProfile == null)
                {
                    return;
                }

                var accessToken = AccessToken.CurrentAccessToken.TokenString;
                var request     = new GraphRequest("/" + e.NewProfile.UserID, new NSDictionary("fields", "email,first_name,last_name,picture.type(large)"), accessToken, null, "GET");
                request.Start((connection, result, error) =>
                {
                    // Show the loading overlay on the UI
                    LoadingOverlay.ShowOverlay(View);

                    var userInfo = result as NSDictionary;

                    // Get Facebook avatar image from url
                    var avatarUrl = new NSUrl(userInfo["picture"].ValueForKey(new NSString("data")).ValueForKey(new NSString("url")).ToString());
                    var data      = NSData.FromUrl(avatarUrl);

                    facebookImageData = data;

                    // string facebookAvatar = data.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
                    // facebookAvatar = new NSString(eefacebookAvatar, NSStringEncoding.UTF8); //Encoding.ASCII.GetString(ToByteArray(data));

                    // Add Facebook user to database
                    var user = new UsersModel()
                    {
                        FirstName     = userInfo["first_name"].ToString(),
                        LastName      = userInfo["last_name"].ToString(),
                        Email         = userInfo["email"].ToString().ToLower(),
                        LoginProvider = "Facebook"
                    };

                    // Call REST service to send Json data
                    RestService rs = new RestService();

                    // Get Json data from server in JsonResponseModel format
                    Task <UsersModel> jsonResponeTask = rs.UserLoginAndRegisterJson(user, "register");

                    // If there was an error in PostJsonDataAsync class, display message
                    if (jsonResponeTask == null)
                    {
                        LoadingOverlay.RemoveOverlay();
                        return;
                    }

                    // Get user id from Json after login or display an error
                    GetUserIdFromJson(jsonResponeTask, user);

                    if (error != null)
                    {
                        LoadingOverlay.RemoveOverlay();
                        Console.WriteLine("Error in request. Start Facebook login");
                        return;
                    }
                });
            });

            // Set the Read and Publish permissions you want to get
            loginView = new LoginButton(fbAuthButton.Frame)
            {
                LoginBehavior   = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };

            // Handle actions once the user is logged in
            loginView.Completed += LoginView_Completed;

            // Handle actions once the user is logged out
            loginView.LoggedOut += (sender, e) =>
            {
                // Set logout User Defaults
                var plist = NSUserDefaults.StandardUserDefaults;
                plist.SetBool(false, "isUserLoggedIn"); // set flag that user logged out
                plist.SetString("", "userId");
                plist.Synchronize();
            };

            // Use your System Account of Settings
            //loginButton.LoginBehavior = LoginBehavior.SystemAccount;

            // Add views to main view
            View.AddSubview(loginView);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            loginButton = new LoginButton(new CGRect(80, 120, 220, 46))
            {
                LoginBehavior = LoginBehavior.SystemAccount,
                ReadPermissions = readPermissions.ToArray()
            };

            loginButton.Completed += (sender, e) => {
                if (e.Error != null)
                {
                    Debug.WriteLine(e.Error.Description);
                }

                if (e.Result != null && e.Result.IsCancelled)
                {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) => {
                // Handle your logout
                nameLabel.Text = "";
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView(new CGRect(80, 200, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel(new CGRect(20, 319, 280, 21))
            {
                TextAlignment = UITextAlignment.Center,
                BackgroundColor = UIColor.Clear
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null)
            {
                var request = new GraphRequest("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null)
                    {
                        new UIAlertView("Error...", error.Description, null, "Ok", null).Show();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;
                    nameLabel.Text = userInfo["name"].ToString();
                });
            }

            // Add views to main view
            View.AddSubview(loginButton);
            View.AddSubview(pictureView);
            View.AddSubview(nameLabel);

            // Perform any additional setup after loading the view, typically from a nib.
            ConfigureView();
        }
Example #23
0
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            List <string> readPermissions = new List <string> {
                "public_profile", "email"
            };

            Profile.Notifications.ObserveDidChange((sender, e) =>
            {
                if (e.NewProfile == null)
                {
                    return;
                }

                nameLabel.Text          = e.NewProfile.Name;
                pictureView.PictureMode = ProfilePictureMode.Square;

                User u = new User();

                u.Name     = e.NewProfile.FirstName;
                u.ImageUrl = e.NewProfile.ImageUrl(ProfilePictureMode.Square, new CGSize(70, 70)).ToString();

                App.SaveUser(u);
            });

            loginButton = new LoginButton(new CGRect(80, 20, 220, 46))
            {
                LoginBehavior   = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };

            nameLabel = new UILabel();

            pictureView = new ProfilePictureView(new CGRect(80, 90, 220, 46));

            loginButton.TouchUpInside += (sender, e) =>
            {
            };

            loginButton.Completed += (sender, e) =>
            {
                App.SaveToken(AccessToken.CurrentAccessToken.TokenString);
                App.SuccessfulLoginAction.Invoke();

                if (e.Error != null)
                {
                    // Handle if there was an error
                    new UIAlertView("Login", e.Error.Description, null, "Ok", null).Show();
                    return;
                }

                if (e.Result.IsCancelled)
                {
                    // Handle if the user cancelled the login request
                    new UIAlertView("Login", "The user cancelled the login", null, "Ok", null).Show();
                    return;
                }
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) =>
            {
                // Handle your logout
                new UIAlertView("Login", "Logout", null, "Ok", null).Show();
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null)
            {
                var request = new GraphRequest("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start((connection, result, error) =>
                {
                    // Handle if something went wrong with the request
                    if (error != null)
                    {
                        new UIAlertView("Error...", error.Description, null, "Ok", null).Show();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;

                    //App.SaveToken(userInfo["token"].ToString());
                    //nameLabel.Text = userInfo["name"].ToString();
                });
            }

            // Add views to main view
            View.AddSubview(loginButton);
            View.AddSubview(pictureView);
            View.AddSubview(nameLabel);
        }
        private void FinalizeLogin()
        {
            if (AccessToken.CurrentAccessToken != null) {
                InvokeOnMainThread (() => {
                    StatusLabel.Text = "TryingServer_string".Localize ();
                });
                var request = new GraphRequest ("/me?fields=name,id,birthday,first_name,gender,last_name,interested_in,location", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;

                    LettuceServer.Instance.FacebookLogin (userInfo ["id"].ToString (), AccessToken.CurrentAccessToken.TokenString, (theUser) => {
                        InvokeOnMainThread (() => {
                            NavController.PopToRootViewController (true);
                        });
                    });
                });
            } else {
                InvokeOnMainThread (() => {
                    StatusLabel.Text = "FacebookConnectFailed_string".Localize();
                });
            }
        }
Example #25
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			// Perform any additional setup after loading the view, typically from a nib.

			// If was send true to Profile.EnableUpdatesOnAccessTokenChange method
			// this notification will be called after the user is logged in and
			// after the AccessToken is gotten
			Profile.Notifications.ObserveDidChange ((sender, e) => {

				if (e.NewProfile == null)
					return;

				nameLabel.Text = e.NewProfile.Name;
			});

			// Set the Read and Publish permissions you want to get
			loginButton = new LoginButton (new CGRect (80, 20, 220, 46)) {
				LoginBehavior = LoginBehavior.Native,
				ReadPermissions = readPermissions.ToArray ()
			};

			// Handle actions once the user is logged in
			loginButton.Completed += (sender, e) => {
				if (e.Error != null) {
					// Handle if there was an error
					new UIAlertView ("Login", e.Error.Description, null, "Ok", null).Show ();
					return;
				}

				if (e.Result.IsCancelled) {
					// Handle if the user cancelled the login request
					new UIAlertView ("Login", "The user cancelled the login", null, "Ok", null).Show ();
					return;
				}

				// Handle your successful login
				new UIAlertView ("Login", "Success!!", null, "Ok", null).Show ();
			};

			// Handle actions once the user is logged out
			loginButton.LoggedOut += (sender, e) => {
				// Handle your logout
				nameLabel.Text = "";
			};

			// The user image profile is set automatically once is logged in
			pictureView = new ProfilePictureView (new CGRect (80, 100, 220, 220));

			// Create the label that will hold user's facebook name
			nameLabel = new UILabel (new CGRect (80, 340, 220, 21)) {
				TextAlignment = UITextAlignment.Center,
				BackgroundColor = UIColor.Clear
			};

			// If you have been logged into the app before, ask for the your profile name
			if (AccessToken.CurrentAccessToken != null) {
				var request = new GraphRequest ("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
				request.Start ((connection, result, error) => {
					// Handle if something went wrong with the request
					if (error != null) {
						new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
						return;
					}

					// Get your profile name
					var userInfo = result as NSDictionary;
					nameLabel.Text = userInfo ["name"].ToString ();
				});
			}

			// Add views to main view
			View.AddSubview (loginButton);
			View.AddSubview (pictureView);
			View.AddSubview (nameLabel);
		}
Example #26
0
        protected override void OnElementChanged(ElementChangedEventArgs <FacebookLoginButton> e)
        {
            base.OnElementChanged(e);
            if (Element == null)
            {
                return;
            }

            var element = Element;

            var token = AccessToken.CurrentAccessToken;

            element.LoggedIn = token != null;


            var control = new LoginButton();

            control.ReadPermissions    = element.ReadPermissions;
            control.PublishPermissions = element.PublishPermissions;
            control.LoginBehavior      = LoginBehavior.Browser;

            SetNativeControl(control);

            control.Completed += (s, ea) =>
            {
                var accessToken = AccessToken.CurrentAccessToken;
                var t           = new GraphRequest("me", new NSDictionary("fields", "id, first_name, email, last_name, picture.width(1000).height(1000)"));
                t.Start((GraphRequestConnection connection, Foundation.NSObject result, Foundation.NSError error) =>
                {
                    var graphObject = result as NSDictionary;

                    var id         = string.Empty;
                    var first_name = string.Empty;
                    var email      = string.Empty;
                    var last_name  = string.Empty;
                    var url        = string.Empty;

                    try
                    {
                        id = graphObject.ValueForKey(new NSString("id"))?.ToString();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                    try
                    {
                        first_name = graphObject.ValueForKey(new NSString("first_name"))?.ToString();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                    try
                    {
                        email = graphObject.ValueForKey(new NSString("email"))?.ToString();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                    try
                    {
                        last_name = graphObject.ValueForKey(new NSString("last_name"))?.ToString();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                    try
                    {
                        url = ((graphObject.ValueForKey(new NSString("picture")) as NSDictionary).ValueForKey(new NSString("data")) as NSDictionary).ValueForKey(new NSString("url")).ToString();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                    element.SendShowingLoggedInUser(
                        new FacebookUser(id, accessToken.TokenString, first_name, last_name, email, url)
                        );
                });
            };

            control.LoggedOut += (s, ea) =>
            {
                element.SendShowingLoggedOutUser();
            };

            if (element.PublishPermissions != null)
            {
                control.PublishPermissions = element.PublishPermissions;
            }
            if (element.ReadPermissions != null)
            {
                control.ReadPermissions = element.ReadPermissions;
            }

            MessagingCenter.Subscribe(this, "Login", (s) =>
            {
                Login();
            }, element);

            MessagingCenter.Subscribe(this, "Logout", (s) =>
            {
                Logout();
            }, element);

            if (element.LoggedIn)
            {
                var accessToken = AccessToken.CurrentAccessToken;
                var t           = new GraphRequest("me", null);
                t.Start((GraphRequestConnection connection, Foundation.NSObject result, Foundation.NSError error) =>
                {
                    var graphObject = result as NSDictionary;
                    var id          = graphObject.ObjectForKey(new NSString("id")).ToString();

                    element.SendShowingLoggedInUser(
                        new FacebookUser(id, accessToken.TokenString, graphObject.ObjectForKey(new NSString("name")).ToString(), graphObject.ObjectForKey(new NSString("name")).ToString(), graphObject.ObjectForKey(new NSString("name")).ToString(), string.Format("http://graph.facebook.com/{0}/picture?type=large", id))
                        );
                });
            }
        }