简体   繁体   English

通过Facebook iOS Parse.com登录用户

[英]Login user through Facebook iOS Parse.com

I am trying to login a user through facebook in my parse.com app. 我正在尝试在parse.com应用程序中通过Facebook登录用户。 I have all the ids and appdelegate methods in place. 我有所有的id和appdelegate方法。

I have created a view in the storyboard and made that a facebook login button and then i have connected it to my .h file as a IBAction. 我在情节提要板上创建了一个视图,并创建了一个Facebook登录按钮,然后将其作为IBAction连接到我的.h文件。

my code: 我的代码:

- (IBAction)fblogin:(FBSDKLoginButton *)sender {
    [PFFacebookUtils logInInBackgroundWithReadPermissions:@[@"public_profile", @"email"] block:^(PFUser *user, NSError *error) {
        if (error) {
                   //     NSLog(@"Uh oh. The user cancelled the Facebook login.");
            UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:@"Sorry" message:[error.userInfo objectForKey:@"error"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

            [alertVeiw show];

        } else if (!user) {
            UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"You cancelled Login, try again!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

            [alertVeiw show];
        }else {
                 //       NSLog(@"User logged in through Facebook!");
           // [self dismissViewControllerAnimated:YES completion:NULL];

            FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"first_name, last_name, email, public_profile"}];
            [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
             {
                 if (error)
                 {
                     UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:@"Sorry" message:[error.userInfo objectForKey:@"error"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

                     [alertVeiw show];

                 } else if ([[error userInfo][@"error"][@"type"] isEqualToString: @"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
                     //   NSLog(@"The facebook session was invalidated");
                     [PFFacebookUtils unlinkUserInBackground:[PFUser currentUser]];
                 }
                 else {

                     NSDictionary *userData = (NSDictionary *)result;
                     //   [self requestFacebookUser:user];

                     NSString *name = userData[@"name"];
                     NSString *email = userData[@"email"];

                     user.username = name;
                     user.email = email;
                     [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
                      {
                          if (error)
                          {
                              UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:@"Sorry" message:[error.userInfo objectForKey:@"error"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

                              [alertVeiw show];

                          }
                          else {
                              // [self dismissViewControllerAnimated:NO completion:nil];
                              //[self.navigationController popToRootViewControllerAnimated:NO];
                              [self performSegueWithIdentifier:@"inbox" sender:self];
                          }
                      }];
                 }
             }];
        }
    }];
}

The faccebook web page opens when i press login facebook button then we sign in and then nothing happens. 当我按下登录Facebook按钮然后我们登录然后没有任何反应时,faccebook网页打开。

Please help me implement facebook login step by step correctly. 请帮助我正确地逐步实现Facebook登录。

EDIT: 编辑:

app delegate: 应用程序委托:

[PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions];

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                          openURL:url
                                                sourceApplication:sourceApplication
                                                       annotation:annotation];
}

applicationWillEnterForeGround:
[FBSDKAppEvents activateApp];

then: 然后:

along with your(SanitLee) answer i have these methods: 连同您的(SanitLee)答案,我有以下方法:

- (void)loginViewFetchedUserInfo:(FBSDKLoginManager *)loginView
                            user:(FBSDKProfile*)user {

}

-(void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error{
  //  [self performSegueWithIdentifier:@"inbox" sender:self];
}

-(void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton{

}

-(void)loginButtonClicked{
}

i also get this error on whose view is not in the window hierarchy! 我也收到关于其视图不在窗口层次结构中的错误!

Here's how I did it and it works for me. 这是我的操作方式,它对我有用。 Firstly, import this in your m file: 首先,将其导入您的m文件中:

#import <ParseFacebookUtils/PFFacebookUtils.h>//fb login for parse

Then the following codes should do what you want: 然后,以下代码应执行您想要的操作:

- (IBAction)loginButtonTouchHandler:(id)sender {          
  NSArray *permissionsArray = @[ @"user_about_me", @"user_relationships", @"user_birthday", @"user_location"];
  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  [PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
  if (!user) {
     NSString *errorMessage = nil;
     if (!error) {
        NSLog(@"Uh oh. The user cancelled the Facebook login.");
        errorMessage = NSLocalizedString(@"Uh oh. The user cancelled the Facebook login.", nil);
     } else {
        NSLog(@"Uh oh. An error occurred: %@", error);
        errorMessage = [error localizedDescription];
     }
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Log In Error", nil) message:errorMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Dismiss", nil), nil];
     [MBProgressHUD hideHUDForView:self.view animated:YES];
     [alert show];  
  } else {
     if (user.isNew) {
        NSLog(@"User with facebook signed up and logged in!");
        [self _loadData];               
     } else {
        NSLog(@"User with facebook logged in!");
     }
     [MBProgressHUD hideHUDForView:self.view animated:YES];
     [self _presentNextViewControllerAnimated:YES];
  } 
  }];
}

- (void)_presentNextViewControllerAnimated:(BOOL)animated {
  PAWWallViewController *wallViewController = [[PAWWallViewController alloc] initWithNibName:nil bundle:nil];
  [(UINavigationController *)self.presentingViewController pushViewController:wallViewController animated:NO];
  [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (void)_loadData {
  FBRequest *request = [FBRequest requestForMe];
  [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
  if (!error) {
     PFUser *user = [PFUser currentUser];
     NSDictionary *userData = (NSDictionary *)result;
     NSString *facebookID = userData[@"id"];
     NSString *name = userData[@"name"];
     NSString *email = userData[@"email"];
     NSString *location = userData[@"location"][@"name"];
     NSString *gender = userData[@"gender"];
     NSString *birthday = userData[@"birthday"];
     NSString *relationship = userData[@"relationship_status"];
     NSString *facebookLink = [NSString stringWithFormat:@"Facebook.com/%@", facebookID];
     NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large&return_ssl_resources=1", facebookID]];  
     NSLog(@"facebookID --> %@", facebookID);
     NSLog(@"name --> %@", name);
     NSLog(@"email --> %@", email);
     //for profile image
     NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
     // Run network request asynchronously
     [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,     NSData *data, NSError *connectionError) {
     if (connectionError == nil && data != nil) {
        PFFile *userImageFile = [PFFile fileWithName:@"userImage.jpg" data:data];
        if (userImageFile) [user setObject:userImageFile forKey:kPAWParseUserImageKey];
     }

     [user setObject:facebookID forKey:kPAWParseUsernameKey]; //initially use fb id as username to avoid duplication
     [user setObject:name forKey:kPAWParseRealnameKey];
     [user setObject:facebookLink forKey:kPAWParseFacebookKey];

     [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
     if (!error) {
        if (succeeded) {
           NSLog(@"fb user saved successfully");
        }
     } else {
        NSLog(@"fb user saved unsuccessfully");
     }
     }];
   }];

   } else if ([[[[error userInfo] objectForKey:@"error"] objectForKey:@"type"]
                isEqualToString: @"OAuthException"]) {
        NSLog(@"The facebook session was invalidated");

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Log out of Spotpost?", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Log out", nil) otherButtonTitles:NSLocalizedString(@"Cancel", nil), nil];
        [alertView show];

   } else {
     NSLog(@"Some other error: %@", error);
   }
   }];
}

And here is how I did config in app delegate: 这是我在应用程序委托中进行配置的方法:

#import <ParseFacebookUtils/PFFacebookUtils.h> //fb login for parse
....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  ...
  [PFFacebookUtils initializeFacebook]; //fb login for parse 
  return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  ....
  [FBAppCall handleDidBecomeActiveWithSession:[PFFacebookUtils session]]; //fb login for parse
}

- (BOOL)application:(UIApplication *)application
        openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
     annotation:(id)annotation {
  return [FBAppCall handleOpenURL:url
              sourceApplication:sourceApplication
                    withSession:[PFFacebookUtils session]];
}


- (void)applicationWillTerminate:(UIApplication *)application {
  [[PFFacebookUtils session] close];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM