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.
- Right-click
info.plist
, and choose Open As Source Code. - 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>
- 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>
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;
}
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;
}
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
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.
}
}
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"];
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登陸的完整流程,