项目由 Objective-C 写成,而 facebook 新 sdk 由 swift 写的。
需要用到混编。
官网地址:Facebook-ios-sdk
1. 导入库
按官网文档说的做就行。
添加目标要选,不然不能用。如果没有选,重新加也就可以。
添加成功后,这里可以看到。需要删除也在这里删除。
2.项目设置
建一个空的 .swift 文件,让项目支持 swift 混编。
facebook 用到的 framework 给加上:
AuthenticationServices.framework、SafariServieces.framework
解决引用错误:
3.加代码
引用头文件,AuthenticationServices,SafariServices 需要先加,不然 sdk 编译报错。FBSDKAccessToken.h, FBSDKAuthenticationToken.h 需要用 include,不然找不到。
#import <AuthenticationServices/AuthenticationServices.h>
#import <SafariServices/SafariServices.h>
#import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
#import <FBSDKLoginKit/FBSDKLoginKit-Swift.h>
#include <FBSDKCoreKit/FBSDKAuthenticationToken.h>
#include <FBSDKCoreKit/FBSDKAccessToken.h>
初始化 sdk:
- (void)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
[FBSDKApplicationDelegate.sharedInstance initializeSDK];
...
}
+(NSString*) getPushKeyDeviceToken{
return [TxApnsProxy getDeviceToken];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
...
if ([[FBSDKApplicationDelegate sharedInstance] application:application openURL:url options:options]) {
return YES;
}
return YES;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(nullable NSString *)sourceApplication
annotation:(nonnull id)annotation
{
...
[[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
return YES;
}
登录调用:
注意调用登录模式:
FBSDKLoginConfiguration 中 tracking 为 FBSDKLoginTrackingLimited 时,result.token 会是空的。但是 result.authenticationToken 会有值。
@property(nonnull,strong) FBSDKLoginManager* fbLogin;
@synthesize fbLogin = _fbLogin;
-(void) init
{
// 初始化的时候加
self.fbLogin = [FBSDKLoginManager new];
}
-(void) login
{
FBSDKLoginConfiguration *configuration = [[FBSDKLoginConfiguration alloc] initWithPermissions:@[@"public_profile", @"email"]
tracking:FBSDKLoginTrackingEnabled
nonce:@"123"];
[self.fbLogin logInFromViewController:[u8sdk (GetViewController)]
configuration:configuration
completion:^(FBSDKLoginManagerLoginResult * result, NSError *error) {
if (!error && !result.isCancelled) {
// Login successful-把 toekn 给服务器校验
NSDictionary *callbackDict = [NSDictionary dictionaryWithObjectsAndKeys:result.token.tokenString, @"token", nil];
[self (eventUserLogin):callbackDict];
} else {
NSDictionary *callbackDict = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"error", nil];
[self (eventUserLogin):callbackDict];
}
}];
}