IOS 集成Facebook登陆及获取用户信息

首先做Facebook登陆的时候一定要进行VPN登陆,确认翻墙成功后在进行登陆。

Facebook登陆官网:Facebook官网方便察阅资料

1,该项目仅仅是作为接入Facebook登陆的示例项目,打开Xcode创建一个单页应用。

2:在Facebook官网上下载iOS SDK  地址:SDK下载地址

解压该zip文件得到以下目录结构的文件

将图示的四个文件拖拽到你的Xcode项目工程里面去这些就是你项目需要用到的一些第三方库文件

然后双击你的项目来到项目配置找到Build Setting选项卡进行相关的配置首先将上面的依赖包进行配置

找到Framework Search Paths在其下添加你所依赖的framework的路径我的项目放到了桌面上:

这样的话做登陆的时候当你引入包的时候就不会无故的报错了

3:以下可以参考Facebook官网的文档进行操作:

 Configure Your info.plist

Configure the information property list file (info.plist) with an XML snippet that contains data about your app.

  1. Right-click info.plist, and choose Open As Source Code.
  2. Copy and paste the following XML snippet into the body of your file ( <dict>...</dict>).
    <key>CFBundleURLTypes</key>
    <array>
      <dict>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>fb[APP_ID]</string>
      </array>
      </dict>
    </array>
    <key>FacebookAppID</key>
    <string>[APP_ID]</string>
    <key>FacebookDisplayName</key>
    <string>[APP_NAME]</string>

    Copy Code

  3. To use any of the Facebook dialogs (e.g., Login, Share, App Invites, etc.) that can perform an app switch to Facebook apps, your application's info.plist also needs to include:
    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>fbapi</string>
      <string>fb-messenger-share-api</string>
      <string>fbauth2</string>
      <string>fbshareextension</string>
    </array>

    Copy Code

5. Connect Your App Delegate

Add the following to your AppDelegate class. This initializes the SDK when your app launches, and lets the SDK handle results from the native Facebook app when you perform a Login or Share action.

//  AppDelegate.m
#import <FBSDKCoreKit/FBSDKCoreKit.h>

- (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  [[FBSDKApplicationDelegate sharedInstance] application:application
    didFinishLaunchingWithOptions:launchOptions];
  // Add any custom logic here.
  return YES;
}

- (BOOL)application:(UIApplication *)application 
            openURL:(NSURL *)url 
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
    openURL:url
    sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
    annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
  ];
  // Add any custom logic here.
  return handled;
}
    

Copy Code

Note that application:openURL:options: is only available in iOS 9 and above. If you are building with an older version of the iOS SDK, you can use:

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

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
    openURL:url
    sourceApplication:sourceApplication
    annotation:annotation
  ];
  // Add any custom logic here.
  return handled;
} 

Copy Code

6. Add Facebook Login to Your Code

Use the Facebook Login button in your iOS app.

6a. Add Facebook Login to Your Code

To add a Facebook-branded Login button to your app, add the following code snippet to a view controller.

// Add this to the header of your file, e.g. in ViewController.m 
// after #import "ViewController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

// Add this to the body
@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
  // Optional: Place the button in the center of your view.
  loginButton.center = self.view.center;
  [self.view addSubview:loginButton];
}

@end

Copy Code

At this point you should be able to run your app and log in using the Facebook Login button.

6b. Check Current Login Status

Your app can only have one person logged in at a time. We represent each person logged into your app with the [FBSDKAccessToken currentAccessToken].

The FBSDKLoginManager sets this token for you and when it sets currentAccessToken it also automatically writes it to a keychain cache.

The FBSDKAccessToken contains userID which you can use to identify the user.

You should update your view controller to check for an existing token at load. This eliminates an unnecessary app switch to Facebook if someone already granted permissions to your app:

- (void)viewDidLoad
{
  [super viewDidLoad];
  if ([FBSDKAccessToken currentAccessToken]) {
   // User is logged in, do work such as go to next view controller. 
  }
}

Copy Code

6c. Ask for Permissions

When using Facebook Login, your app can ask for permissions on a subset of a person's data.

Read Permissions for Facebook Login Button

To request additional read permissions, set the readPermissions property on the FBSDKLoginButton object.

// Extend the code sample from 6a. Add Facebook Login to Your Code
// Add to your viewDidLoad method:
loginButton.readPermissions = @[@"public_profile", @"email"];

Copy Code

The user will be prompted to grant your app with the requested permissions. Note that some permissions will require a Login Review. See Managing Permissions for more information on permissions.

#import <Foundation/Foundation.h>
#import "LoginView.h"
#import <FBSDKCoreKit/FBSDKGraphRequest.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "ViewController.h"
@interface LoginView()
@property FBSDKAccessToken * access_token;
@end
@implementation LoginView
- (void) viewDidLoad{
    [super viewDidLoad];
    //check login status
    
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"欢迎来到小游戏世界!!!");
    //兼容 c programming launge
    printf("first ios app !!! %s","helloworld");
    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.center = self.view.center;
    //button get permessions for our app
    loginButton.readPermissions = @[@"public_profile",@"email",@"user_friends"];
    //类的实例化
    //    ViewController *vc=[[ViewController alloc] init];
    //    [ViewController sum:1 and:2];
    [self.view addSubview:loginButton];
    //login success and return an accessToken for your app
    NSLog(@"current access token is %@",[FBSDKAccessToken currentAccessToken]);
    //登陆按钮管理器用于管理登陆按钮的响应事件和Facebook传递的数据
    FBSDKLoginManager * loginManager = [[FBSDKLoginManager alloc] init];
    [loginManager logInWithReadPermissions:@[@"public_profile",@"email",@"user_friends"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult * result,NSError * error){
        //登陆回调
        if(result){
            NSLog(@"result is %@ ",result);
            //登陆成功
            self.access_token = [FBSDKAccessToken currentAccessToken];
            [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
             startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                 if (!error) {
                     NSLog(@"fetched user:%@", result);
                     //进入游戏界面 view 跳转
                     //                 UIImagePickerController *uv=[[UIImagePickerController alloc] init];
                     //                 uv.delegate=self;
                     UIWindow * window=[[UIApplication sharedApplication] keyWindow];
                     NSLog(@"window is%@",window.rootViewController.view);
                     //                 NSLog(@"window is%@",window.rootViewController.nibName);
                     //                 vc=window.rootViewController.view;
                     //                 MainViewController * main = [[self storyboard] instantiateViewControllerWithIdentifier:@"game"];
                     UIViewController * loginVc = [[self storyboard] instantiateViewControllerWithIdentifier:@"login"];
                     NSLog(@"loginVc is %@",loginVc);
                     ViewController * gameView = [[ViewController alloc] init];
                     NSLog(@"gameView is %@",gameView);
                     UIViewController * gameVc = [[self storyboard] instantiateViewControllerWithIdentifier:@"game"];
                     NSLog(@"gameVc is %@",gameVc);
                     window.rootViewController = gameView;
                     NSLog(@"jump to game scene");
                 }
             }];
        }
        if(error){
            NSLog(@"error is %@",error);
        }
    }];
    
    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSURL * url = [NSURL URLWithString:@"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"];
//        NSData * data = [[NSData alloc]initWithContentsOfURL:url];
//        UIImage *image = [[UIImage alloc]initWithData:data];
//        if (data != nil) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//
//            });
//        }
//    });
    //登陆的时候是一个耗时操作需要异步处理
//        if([FBSDKAccessToken currentAccessToken]){
//            //        NSLog(@"login successful %@",[FBSDKAccessToken currentAccessToken]);
//            //        NSLog(@"accessToken is %@",[FBSDKAccessToken currentAccessToken]);
//
//            //        printf("accessToken is %s ",[FBSDKAccessToken currentAccessToken]);
//    }
    
}
@end

4:在这里贴出AppDelegate.m文件:及获取用户信息的代码

然后就是视图控制器中的代码了:

如果完成 登陆之后需要跳转页面的话就要设置登陆按钮回调函数

至此我们完成了Facebook登陆的完整流程,

猜你喜欢

转载自blog.csdn.net/lck8989/article/details/82630702