简体   繁体   English

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

[英]iOS : Login with Facebook and open Native Facebook app

  • I Want open facebook application at login time that already install in the device for login authentication, but always open in the Safari browser. 我希望在登录时打开facebook应用程序,该应用程序已安装在设备中进行登录验证,但始终在Safari浏览器中打开。

- facebook button click - 点击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"];
                         }
                     }
                 }];
            }
        }

-here to fetch user info - 获取用户信息

        -(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);
                     }
                 }];

        }
  • I Want to open facebook application for login with facebook. 我想用Facebook登录facebook应用程序登录。

From V4.6.0 it won't redirect to fb app. 从V4.6.0它不会重定向到fb应用程序。 See below 见下文

(v4.6.0 - September 10, 2015) In addition, the SDK dialogs such as Login, Like, Share Dialogs automatically determine the best UI based on the device, including SFSafariViewController instead of Safari. (v4.6.0 - 2015年9月10日)此外,SDK对话框(如Login,Like,Share Dialogs)会根据设备自动确定最佳UI,包括SFSafariViewController而不是Safari。 Follow the our Preparing for iOS 9 guide. 按照我们的准备iOS 9指南。

在此输入图像描述

Please Use FBLoginView as Facebook SignIn button It automatically detects Facebook app & u can able to login with facebook. 请使用FBLoginView作为Facebook登录按钮它会自动检测Facebook应用程序,您可以使用Facebook登录。 FBLoginView class available in Facebook SDK. Facebook SDK中提供FBLoginView类。

Please set info.plist parameters properly, you may have not provided the URLs like this 请正确设置info.plist参数,您可能没有提供这样的URL

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

and

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

If you are not able to achieve what you want,then you can use these classes. 如果您无法达到您想要的效果,那么您可以使用这些类。

Header File - 头文件 -

//
//  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

and Implementation file is - 和实施文件是 -

//
//  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

Add FBSDKCoreKit.Framework and FBSDKLoginKit.Framework in your project and set your app Delefate like this - 在您的项目中添加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];
}

now you can use these classes as on any event suppose on button click- 现在你可以使用这些类作为按钮点击上的任何事件 -

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

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

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