前言:
近日接Facebook SDK iOS时发现Facebook官网最新的SDK已经部分改成Swift语言了,官方文档也是只看到Swift的相关代码,没找到OC的代码,但是我要接的项目都是OC语言写的,为此捣鼓了半天总算成功接好了,记录一下以免忘记。
正文:
1.首先要登录Facebook账号把项目相关的配置好,这些步骤根据官方文档一步步做就好了,很简单不多做赘述。
官方文档
2.将SDK导入项目中,方法很多,我是用cocoapod导入
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'
基本上导入这三个就够了,具体根据项目需求导入。
3.由于Facebook SDK很多改成Swift的了,而我们的项目还是OC的,所以需要混编。
-
添加 Swift 文件:
- 在 Xcode 的左侧项目导航栏中右键点击项目名称,选择
New File
。 - 选择
Swift File
,然后点击Next
。 - 输入文件名,然后点击
Create
。
- 在 Xcode 的左侧项目导航栏中右键点击项目名称,选择
-
创建桥接头文件:
- 在添加第一个 Swift 文件时,Xcode 会询问是否创建一个桥接头文件(Bridging Header)。选择
Yes
。 - Xcode 会自动创建一个名为
YourProjectName-Bridging-Header.h
的文件。你可以在项目的导航栏中找到它。
- 在添加第一个 Swift 文件时,Xcode 会询问是否创建一个桥接头文件(Bridging Header)。选择
桥接头文件创建完之后就可以开始编写Facebook的相关接口代码了。
首先我们创建一个名为FacebookManager的头文件和 OC文件。
FacebookManager.h相关代码如下:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <AuthenticationServices/AuthenticationServices.h>
#import <SafariServices/SafariServices.h>
#import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
#import <FBSDKLoginKit/FBSDKLoginKit-Swift.h>
#import <FBSDKShareKit/FBSDKShareKit-Swift.h>
#include <FBSDKCoreKit/FBSDKAuthenticationToken.h>
#include <FBSDKCoreKit/FBSDKAccessToken.h>
/**
* @class FacebookManager
* @brief 一个管理 Facebook 登录、用户信息、分享和应用事件的视图控制器类。
*
* FacebookManager 类提供了处理各种与 Facebook 相关功能的方法,
* 包括登录、检查登录状态、获取用户信息、分享内容和记录应用事件。
* 该类实现了 FBSDKSharingDelegate 协议来处理分享结果。
*/
@interface FacebookManager : UIViewController <FBSDKSharingDelegate>
-(void)login; //该方法触发 Facebook 登录流程,允许用户登录他们的 Facebook 账户.
-(BOOL)checkLogin; //该方法验证用户的登录状态,并返回一个布尔值指示用户是否已登录。
-(BOOL)checkInstall; //该方法确定用户设备上是否安装了 Facebook 应用。
-(void)getUserInfo; //该方法从用户的 Facebook 账户中获取并处理用户的个人资料信息。
-(void)getAppFriendInfo; //该方法获取使用该应用的朋友列表,并处理他们的信息。
-(void)logout; //fb登出
-(void)shareFb:(NSString *)jsonStr; //在Facebook 上分享指定内容。
-(void)checkMessanger:(NSString *)jsonStr; //该方法验证是否安装了 Facebook Messenger 应用
-(void)inviteMessanger:(NSString *)jsonStr; //通过 Facebook Messenger 向指定接收者发送邀请
-(void)appEventLogger:(NSString *)eventType; //使用指定的事件类型记录应用事件。
@end
FacebookManager类相关代码如下:
导入相关头文件
#import "FacebookManager.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import <SafariServices/SafariServices.h>
#import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
#import <FBSDKLoginKit/FBSDKLoginKit-Swift.h>
#import <FBSDKShareKit/FBSDKShareKit-Swift.h>
#include <FBSDKCoreKit/FBSDKAuthenticationToken.h>
#include <FBSDKCoreKit/FBSDKAccessToken.h>
#include <FBSDKCoreKit/FBSDKGraphRequest.h>
#include <FBSDKCoreKit/FBSDKAppEvents.h>
实现相关接口:
@implementation FacebookManager
//fb登录接口以及处理登录相关回调
- (void)login {
NSLog(@"oc Facebook login");
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithPermissions:@[@"public_profile", @"email", @"user_friends"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(@"Facebook login error: %@", error.localizedDescription);
//登录发生错误
} else if (result.isCancelled) {
NSLog(@"Facebook login cancelled");
//用户取消操作
} else {
// 登录成功,可以进行进一步的操作
NSLog(@"Facebook login success");
//在此处与JS层交互,传回FB登录成功的消息
}
}];
}
// 检查是否已登录
- (BOOL)checkLogin {
FBSDKAccessToken *accessToken = [FBSDKAccessToken currentAccessToken];
NSLog(@"fbtest: accessToken: %@", accessToken);
BOOL isLoggedIn = accessToken != nil && ![accessToken isExpired];
NSLog(@"fbtest: checkLogin: %d", isLoggedIn);
return isLoggedIn;
}
//检测用户手机是否有安装Facebook应用
- (BOOL)checkInstall {
NSURL *facebookURL = [NSURL URLWithString:@"fb://"];
if ([[UIApplication sharedApplication] canOpenURL:facebookURL]) {
return YES;
} else {
return NO;
}
}
//获取用户信息(id(类似于微信小游戏的openid), name, email, picture.type(large)(这个是头像的信息))
- (void)getUserInfo {
NSLog(@"fbtest: getUserInfo");
FBSDKAccessToken *accessToken = [FBSDKAccessToken currentAccessToken];
NSLog(@"fbtest: getUserId: %@", accessToken.userID);
if (accessToken == nil || [accessToken isExpired]) {
NSLog(@"Error: Access token is null or expired.");
return;
}
// 创建 Graph API 请求
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me"
parameters:@{@"fields": @"id, name, email, picture.type(large)"}
tokenString:accessToken.tokenString
version:nil
HTTPMethod:@"GET"];
[request startWithCompletion:^(id<FBSDKGraphRequestConnecting> connection, id result, NSError *error) {
if (!error) {
NSLog(@"fbtest: onCompleted: %@", result);
NSError *jsonError = nil;
//将result转成jsonData
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:&jsonError];
if (!jsonError) {
//将jsonData转成JSON字符串
NSString *ret = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"fbtest: getUserInfo ret: %@", ret);
// 在此处将用户信息返回给 JSB
//ret.id就是用户id
//ret.name就是用户名
//ret.picture.data.url就是用户的FB头像url
} else {
NSLog(@"fbtest: getUserInfo JSON error: %@", jsonError);
}
} else {
NSLog(@"fbtest: getUserInfo error: %@", error);
}
}];
}
//获取用户的好友信息
- (void)getAppFriendInfo {
NSLog(@"fbtest: getAppFriendInfo");
FBSDKAccessToken *accessToken = [FBSDKAccessToken currentAccessToken];
NSLog(@"fbtest: getUserId: %@", accessToken.userID);
NSLog(@"fbtest: Permissions: %@", accessToken.permissions);
if (accessToken == nil || [accessToken isExpired]) {
NSLog(@"Error: Access token is null or expired.");
// 处理访问令牌为空或过期的情况
return;
}
// 创建 Graph API 请求
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me/friends"
parameters:@{@"fields": @"id, name, picture.type(large)"}
tokenString:accessToken.tokenString
version:nil
HTTPMethod:@"GET"];
[request startWithCompletion:^(id<FBSDKGraphRequestConnecting> connection, id result, NSError *error) {
if (!error) {
NSLog(@"fbtest: onCompleted: %@", result);
NSError *jsonError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:&jsonError];
if (!jsonError) {
NSString *ret = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"fbtest: getAppFriendInfo ret: %@", ret);
// 在此处将好友信息返回给 JSB
} else {
NSLog(@"fbtest: getAppFriendInfo JSON error: %@", jsonError);
}
} else {
NSLog(@"fbtest: getAppFriendInfo error: %@", error);
}
}];
}
//fb登出
- (void)logout {
NSLog(@"fbtest: logout");
// 实例化 FBSDKLoginManager 并调用 logOut 方法
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logOut];
// 通知 JavaScript 端
}
//fb分享
- (void)shareFb:(NSString *)jsonStr {
NSLog(@"fbtest share: %@", jsonStr);
NSError *jsonError = nil;
//将json字符串转成JSON
id json = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
NSLog(@"fbtest: JSON parsing error: %@", jsonError);
// Dispatch error event
return;
}
int shareType = [json[@"shareType"] intValue];
NSString *url = json[@"shareUrl"];
NSLog(@"fbtest share1: %d", shareType);
NSLog(@"fbtest share2: %@", url);
if (shareType == 0) {
FBSDKShareLinkContent*linkContent = [[FBSDKShareLinkContent alloc]init];
linkContent.contentURL= [NSURL URLWithString:url];
FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc] initWithViewController:self content:linkContent delegate:self];
shareDialog.mode = FBSDKShareDialogModeNative;
if (![shareDialog canShow]) {
shareDialog.mode = FBSDKShareDialogModeWeb;
}
shareDialog.shareContent = linkContent;
[shareDialog show];
NSLog(@"fbtest: shareUrl ShareLinkContent");
} else {
// Dispatch unsupported share type event
}
}
//检测messenger
- (void)checkMessanger:(NSString *)jsonStr {
NSLog(@"fbtest checkMessanger: %@", jsonStr);
NSError *jsonError = nil;
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
if (!jsonData) {
NSLog(@"fbtest: Error creating JSON data from string");
return;
}
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
NSLog(@"fbtest: JSON parsing error: %@", jsonError);
return;
}
int shareType = [json[@"shareType"] intValue];
NSString *url = json[@"shareUrl"];
NSLog(@"fbtest checkMessanger1: %d", shareType);
NSLog(@"fbtest checkMessanger2: %@", url);
if (shareType == 0) {
FBSDKShareLinkContent *linkContent = [[FBSDKShareLinkContent alloc] init];
linkContent.contentURL = [NSURL URLWithString:url];
FBSDKMessageDialog *messageDialog = [[FBSDKMessageDialog alloc] initWithContent:linkContent delegate:self];
messageDialog.shareContent = linkContent;
if ([messageDialog canShow]) {
NSLog(@"fbtest: checkMessenger ShareLinkContent");
} else {
NSLog(@"fbtest: checkMessenger failed!");
}
} else {
// Dispatch unsupported share type event
}
}
//邀请
- (void)inviteMessanger:(NSString *)jsonStr {
NSLog(@"fbtest invite: %@", jsonStr);
NSError *jsonError = nil;
id json = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
NSLog(@"fbtest: JSON parsing error: %@", jsonError);
// Dispatch error event
return;
}
int shareType = [json[@"shareType"] intValue];
NSString *url = json[@"shareUrl"];
NSLog(@"fbtest invite1: %d", shareType);
NSLog(@"fbtest invite2: %@", url);
if (shareType == 0) {
FBSDKShareLinkContent *linkContent = [[FBSDKShareLinkContent alloc] init];
linkContent.contentURL = [NSURL URLWithString:url];
[FBSDKMessageDialog showWithContent:linkContent delegate:self];
NSLog(@"fbtest: invite ShareLinkContent");
} else {
// Dispatch unsupported share type event
}
}
//事件上报
- (void)appEventLogger:(NSString *)eventType {
NSLog(@"fbtest appEventLogger: %@", eventType);
if ([eventType isEqualToString:@"register"]) {
// 简单上报注册
[FBSDKAppEvents.shared logEvent:FBSDKAppEventNameCompletedRegistration];
} else if ([eventType isEqualToString:@"purchased"]) {
// 上报带有属性和参数的数据
// NSDictionary *params = @{
// FBSDKAppEventParameterNameCurrency: @"USD",
// FBSDKAppEventParameterNameContentType: @"product",
// FBSDKAppEventParameterNameContent: @"[{\"id\": \"1234\", \"quantity\": 2}, {\"id\": \"5678\", \"quantity\": 1}]"
// };
// [FBSDKAppEvents logEvent:FBSDKAppEventNamePurchased valueToSum:54.23 parameters:params];
// 简单上报支付
[FBSDKAppEvents.shared logEvent:FBSDKAppEventNamePurchased];
}
// Dispatch event to script
// Replace the following line with your method to dispatch the event to your script.
}
最后是分享和邀请的监听
#pragma mark - FBSDKSharingDelegate
- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results {
if ([sharer isKindOfClass:[FBSDKShareDialog class]]) {
NSLog(@"fbtest: share onSuccess");
// Dispatch share success event
} else if ([sharer isKindOfClass:[FBSDKMessageDialog class]]) {
NSLog(@"fbtest: invite onSuccess");
// Dispatch invite success event
}
}
- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error {
if ([sharer isKindOfClass:[FBSDKShareDialog class]]) {
NSLog(@"fbtest: share onError %@", error);
// Dispatch share error event
} else if ([sharer isKindOfClass:[FBSDKMessageDialog class]]) {
NSLog(@"fbtest: invite onError %@", error);
// Dispatch invite error event
}
}
- (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
if ([sharer isKindOfClass:[FBSDKShareDialog class]]) {
NSLog(@"fbtest: share onCancel");
// Dispatch share cancel event
} else if ([sharer isKindOfClass:[FBSDKMessageDialog class]]) {
NSLog(@"fbtest: invite onCancel");
// Dispatch invite cancel event
}
}
@end
至此就全部完成啦。