iOS:使用Facebook登录并打开Native Facebook应用程序

时间:2016-05-17 09:48:58

标签: ios facebook

  • 我想在登录时打开facebook应用程序,该应用程序已安装在设备中进行登录验证,但始终在Safari浏览器中打开。

- 点击Facebook按钮

    -(void)loginButtonClicked
        {
            FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];

        //    [login setLoginBehavior:FBSDKLoginBehaviorNative];

                [login logInWithReadPermissions:@[@"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
                 {
                     if (error)
                     {
                         NSLog(@"Login process error");
                     }
                     else if (result.isCancelled)
                     {
                         NSLog(@"User cancelled login");
                     }
                     else
                     {
                         NSLog(@"Login Success");
                         if ([result.grantedPermissions containsObject:@"email"])
                         {
                             NSLog(@"result is:%@",result);
                             [self fetchUserInfo];
                         }
                         else
                         {
        //                     [SVProgressHUD showErrorWithStatus:@"Facebook email permission error"];
                         }
                     }
                 }];
            }
        }

- 获取用户信息的地方

        -(void)fetchUserInfo
        {
            if ([FBSDKAccessToken currentAccessToken])
            {
                NSLog(@"Token is available : %@",[[FBSDKAccessToken currentAccessToken]tokenString]);

                [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name, email"}]
                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                     if (!error)
                     {
                         NSLog(@"results:%@",result);

                         NSString *email = [result objectForKey:@"email"];
                         NSString *userId = [result objectForKey:@"id"];

                         if (email.length >0 )
                         {
                             NSString *accessToken = [[FBSDKAccessToken currentAccessToken] tokenString];
                             [ref authWithOAuthProvider:@"facebook" token:accessToken
                                    withCompletionBlock:^(NSError *error, FAuthData *authData)
                              {
                                        if (error)
                                        {
                                            NSLog(@"Login failed. %@", error);
                                        }
                                        else
                                        {
                                            NSLog(@"Logged in! %@", authData);

                                            //Start you app Todo
                                        }
                         else
                         {
                             NSLog(@"Facebook email is not verified");
                         }
                     }
                     else
                     {
                         NSLog(@"Error %@",error);
                     }
                 }];

        }
  • 我想用facebook登录facebook应用程序登录。

3 个答案:

答案 0 :(得分:5)

从V4.6.0开始,它不会重定向到fb app。见下文

  

(v4.6.0 - 2015年9月10日)此外,SDK对话框如   登录,赞,分享对话框自动确定最佳的基于用户界面   在设备上,包括SFSafariViewController而不是Safari。   按照我们的准备iOS 9指南。

enter image description here

答案 1 :(得分:1)

请使用 FBLoginView作为Facebook登录按钮它会自动检测Facebook应用程序&你可以用facebook登录。 Facebook SDK中提供了 FBLoginView 类。

答案 2 :(得分:1)

请正确设置info.plist参数,您可能没有提供这样的网址

<array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb776035152513539</string>
            </array>
        </dict>
</array>

<key>FacebookAppID</key>
<string>776035152513539</string>

如果您无法达到您想要的效果,那么您可以使用这些类。

标题文件 -

//
//  LxFaceBookHandler.h
//  KickOffSlotMachine
//
//  Created by Prakhar Goyal on 06/08/15.
//  Copyright (c) 2015 LOGICNEXT. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

typedef NS_ENUM(NSInteger,LOGINRESPONSE)
{
    LOGINRESPONSE_ERROR,
    LOGINRESPONSE_CANCEL,
    LOGINRESPONSE_SUCCESS
};

@protocol LxFaceBookHandlerDelegate <NSObject>

-(void)DidLogInWithResponse:(LOGINRESPONSE)type;

@end

@interface LxFaceBookHandler : NSObject

@property(weak,nonatomic)id<LxFaceBookHandlerDelegate>delegate;
-(void)InitFaceBookLogin;

//Called from app Delegate

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

@end

和实施文件是 -

//
//  LxFaceBookHandler.m
//  KickOffSlotMachine
//
//  Created by Prakhar Goyal on 06/08/15.
//  Copyright (c) 2015 LOGICNEXT. All rights reserved.
//

#import "LxFaceBookHandler.h"

@implementation LxFaceBookHandler
@synthesize delegate =  __delegate;

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        __delegate = nil;
    }
    return self;
}

-(void)InitFaceBookLogin;
{
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
     {
         if (error)
         {
             if (__delegate!=nil)
             {
                 if ( [__delegate respondsToSelector:@selector(DidLogInWithResponse:)])
                 {
                     [__delegate DidLogInWithResponse:LOGINRESPONSE_ERROR];
                 }
             }
         }
         else if (result.isCancelled)
         {
             if (__delegate!=nil)
             {
                 if ( [__delegate respondsToSelector:@selector(DidLogInWithResponse:)])
                 {
                     [__delegate DidLogInWithResponse:LOGINRESPONSE_CANCEL];
                 }
             }
         }
         else
         {
             if (__delegate!=nil)
             {
                 if ( [__delegate respondsToSelector:@selector(DidLogInWithResponse:)])
                 {
                     [__delegate DidLogInWithResponse:LOGINRESPONSE_SUCCESS];
                 }
             }

             //             if ([result.grantedPermissions containsObject:@"email"]) {
             //                 // Do work
             //             }
         }
     }];

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                          openURL:url
                                                sourceApplication:sourceApplication
                                                       annotation:annotation];

}

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   return [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

在您的项目中添加FBSDKCoreKit.Framework和FBSDKLoginKit.Framework并设置您的应用程序Delefate,如下所示 -

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor=[UIColor blackColor];

 SplashViewController *rVC = [[SplashViewController alloc] initWithNibName:@"SplashViewController" bundle:nil];

    self.mNavController=[[UINavigationController alloc]initWithRootViewController:rVC];
    [self.mNavController setNavigationBarHidden:YES];

    self.window.rootViewController=self.mNavController;
    [self.window makeKeyAndVisible];

    self.handler = [[LxFaceBookHandler alloc]init];



    [self.handler application:application didFinishLaunchingWithOptions:launchOptions];
    return YES;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [self.handler application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}

现在你可以使用这些类,就像点击按钮时的任何事件一样 -

- (IBAction)FacebookLoginPressed:(UIButton *)sender
{
    App.handler.delegate  = self;
    [App.handler InitFaceBookLogin];
}