登录用户通过Facebook iOS Parse.com [英] Login user through Facebook iOS Parse.com

查看:145
本文介绍了登录用户通过Facebook iOS Parse.com的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Facebook在我的parse.com应用程序登录一个用户。我有所有的ids和appdelegate方法到位。



我在故事板中创建了一个视图,并将其设置为Facebook登录按钮,然后将其连接到我的。 h文件作为IBAction。



我的代码:

   - ( IBAction)fblogin:(FBSDKLoginButton *)sender {
[PFFacebookUtils logInInBackgroundWithReadPermissions:@ [@public_profile,@email] block:^(PFUser * user,NSError * error){
if(error ){
// NSLog(@呃哦,用户取消了Facebook登录。);
UIAlertView * alertVeiw = [[UIAlertView alloc] initWithTitle:@Sorrymessage:[error.userInfo objectForKey:@error] delegate:nil cancelButtonTitle:@OkotherButtonTitles:nil];

[alertVeiw show];

} else if(!user){
UIAlertView * alertVeiw = [[UIAlertView alloc] initWithTitle:@对不起消息:@您已经取消登录,再试一次!委托:nil cancelButtonTitle:@OkotherButtonTitles:nil];

[alertVeiw show];
} else {
// NSLog(@用户通过Facebook登录!);
// [self dismissViewControllerAnimated:YES completion:NULL];

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

[alertVeiw show];

} else if([[error userInfo] [@error] [@type] isEqualToString:@OAuthException]){//由于请求失败,我们可以检查是由于无效会话
// NSLog(@Facebook会话无效);
[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;
[用户saveInBackgroundWithBlock:^(BOOL成功,NSError *错误)
{
如果(错误)
{
UIAlertView * alertVeiw = [[UIAlertView alloc] initWithTitle: @对不起消息:[error.userInfo objectForKey:@error] delegate:nil cancelButtonTitle:@OkotherButtonTitles:nil];

[alertVeiw show];

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

当我按登录Facebook按钮打开faccebook网页,然后我们登录那么什么也没有。



请帮助我正确执行Facebook登录。



编辑:



app delegate:

  [PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions]; 

- (BOOL)应用程序:(UIApplication *)应用程序openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication注释:(id)注释{

return [ [FBSDKApplicationDelegate sharedInstance]应用程序:应用程序
openURL:url
sourceApplication:sourceApplication
注释:注释];
}

applicationWillEnterForeGround:
[FBSDKAppEvents activateApp];

然后:



SanitLee)答案我有这些方法:

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

}

- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)结果错误:(NSError *)错误{
// [self performSegueWithIdentifier:@inboxsender:self];
}

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

}

- (void)loginButtonClicked {
}

我也得到这个错误,其视图不在窗口层次结构中! >

解决方案

这是我做的,它适用于我。
首先,在m文件中导入:

  #import< ParseFacebookUtils / PFFacebookUtils.h> // fb登录解析

然后以下代码应该做你想要的:

   - (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(@呃哦,用户取消了Facebook登录。
errorMessage = NSLocalizedString(@呃哦,用户取消了Facebook登录,nil);
} else {
NSLog(@呃哦发生错误:%@,错误);
errorMessage = [error localizedDescription];
}
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@登录错误,nil)消息:errorMessage委托:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@Dismiss,nil ),nil];
[MBProgressHUD hideHUDForView:self.view animated:YES];
[alert show];
} else {
if(user.isNew){
NSLog(@用户注册并登录!);
[self _loadData];
} else {
NSLog(@用户登录!);
}
[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 - >%@,电子邮件);
// for profile image
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:pictureURL];
//异步运行网络请求
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response,NSData * data,NSError * connectionError){
if(connectionError = = nil&& data!= nil){
PFFile * userImageFile = [PFFile fileWithName:@userImage.jpgdata:data];
if(userImageFile)[user setObject:userImageFile forKey:kPAWParseUserImageKey];
}

[user setObject:facebookID forKey:kPAWParseUsernameKey]; //最初使用fb id作为用户名,以避免重复
[user setObject:name forKey:kPAWParseRealnameKey];
[user setObject:facebookLink forKey:kPAWParseFacebookKey];

[user saveInBackgroundWithBlock:^(BOOL succeeded,NSError * error){
if(!error){
if(succeeded){
NSLog(@fb用户保存成功);
}
} else {
NSLog(@fb用户保存失败);
}
}];
}];

} else if([[[error userInfo] objectForKey:@error] objectForKey:@type]
isEqualToString:@OAuthException]){
NSLog(@Facebook会话无效);

UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@注销Spotpost?,nil)消息:nil delegate:self cancelButtonTitle:NSLocalizedString(@注销,nil) otherButtonTitles:NSLocalizedString(@Cancel,nil),nil];
[alertView show];

} else {
NSLog(@其他一些错误:%@,错误);
}
}];
}

这里是我如何在app代理中配置:

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

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

- (BOOL)应用程序:(UIApplication *)应用程序
openURL:(NSURL *)url
sourceApplication:(NSString * )sourceApplication
注释:(id)注释{
return [FBAppCall handleOpenURL:url
sourceApplication:sourceApplication
withSession:[PFFacebookUtils session]];
}


- (void)applicationWillTerminate :( UIApplication *)应用程序{
[[PFFacebookUtils session] close];
}


I am trying to login a user through facebook in my parse.com app. I have all the ids and appdelegate methods in place.

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.

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.

Please help me implement facebook login step by step correctly.

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:

- (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:

#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];
}

这篇关于登录用户通过Facebook iOS Parse.com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆