ios-facebook接入


title: ios-facebook接入
categories: Ios
tags: [ios, facebook]
date: 2021-02-13 23:31:18
comments: false
mathjax: true
toc: true

ios-facebook接入


前篇

  • 官方
    • GitHub - https://github.com/facebook/facebook-ios-sdk
    • Get Started - Facebook SDK for iOS - https://developers.facebook.com/docs/facebook-login/ios/v2.2?locale=zh_CN&sdk=cocoapods
      • CocoaPods 方式引入 - https://developers.facebook.com/docs/ios/componentsdks#cocoapods, https://developers.facebook.com/docs/ios/use-cocoapods
    • 登录 - https://developers.facebook.com/docs/ios/use-facebook-login
    • 用户数据 - https://developers.facebook.com/docs/ios/get-user-data
    • 分享 - https://developers.facebook.com/docs/ios/share-photos

facebook 接入
  1. 在 facebook 后台 配置 ios 平台, 获取 fb appid

    • store id 可以先随便找一个已存在的填入进去.
  2. CocoaPods 引入几个核心库

    pod 'FBSDKCoreKit', '~> 9.0.1'
    pod 'FBSDKLoginKit', '~> 9.0.1'
    pod 'FBSDKShareKit', '~> 9.0.1'
    
    • pod 工程构建出 静态库丢到 /Users/XXX/Library/Developer/Xcode/DerivedData/Build/Products 对应 真机/模拟器 的目录下, 然项目工程编译时可以链接到静态库

  3. info.plist 文件的 <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>
    
    <key>LSApplicationQueriesSchemes</key>
    <array> <string>fbapi</string> <string>fbapi20130214</string> <string>fbapi20130410</string> <string>fbapi20130702</string> <string>fbapi20131010</string> <string>fbapi20131219</string> <string>fbapi20140410</string> <string>fbapi20140116</string> <string>fbapi20150313</string> <string>fbapi20150629</string> <string>fbapi20160328</string> <string>fbauth</string> <string>fb-messenger-share-api</string> <string>fbauth2</string> <string>fbshareextension</string>
    </array>
    
    1. [APP_ID] 替换 fb appid.
    2. [APP_NAME] 替换为 app 名.
  4. 代码

    1. 在 app 启动完后初始化 sdk

      // AppDelegate.m  
      @implementation AppDelegate
      
      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      	[[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
        return YES;
      }
      
      - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options{
        [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url options:options];
        return YES;
      }
      
    2. iOS 13 将打开网址的功能移到了 SceneDelegate 中

      // SceneDelegate.m
      #import <FBSDKCoreKit/FBSDKCoreKit.h>
      
      @import FacebookCore;
      
      @implementation SceneDelegate
      
      - (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts{
        UIOpenURLContext *context = URLContexts.allObjects.firstObject;
        [FBSDKApplicationDelegate.sharedInstance application:UIApplication.sharedApplication
                                                     openURL:context.URL
                                           sourceApplication:context.options.sourceApplication
                                                  annotation:context.options.annotation];
      }
      
    3. 登录, 登出, 获取用户信息, 展示 登录页面

      #import "FBHelper.h"
      
      #import <FBSDKCoreKit/FBSDKCoreKit.h>
      #import <FBSDKLoginKit/FBSDKLoginKit.h>
      
      @implementation FBHelper
      
      static FBHelper *_sharedIns = nil;
      +(instancetype) shareInstance {
          static dispatch_once_t onceToken;
          dispatch_once(&onceToken, ^{
              _sharedIns = [[self alloc] init] ;
          }) ;
          
          return _sharedIns ;
      }
      
      -(void)showLoginBtn:(UIView*)view{
          FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
          loginButton.center = view.center;
          [view addSubview:loginButton];
      }
      
      -(void)login:(UIViewController*)vc{
          FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
          [login logInWithPermissions:@[@"publish_actions"]
                   fromViewController:vc
                              handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
              if (error) {
                  NSLog(@"--- login fail, err: %@", error);
                  return;
              }
              
              FBSDKAccessToken* accessToken = [FBSDKAccessToken currentAccessToken];
              if (accessToken) {
                  NSLog(@"--- login success, userId: %@, token: %@", accessToken.userID, accessToken.tokenString);
                  return;
              }
              
              NSLog(@"--- login cancel");
          }];
      }
      
      -(void)logout{
          if ([FBSDKAccessToken currentAccessToken]) {
              NSLog(@"--- has accessToken");
              FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
              [login logOut];
          } else {
              NSLog(@"--- no accessToken");
          }
      }
      
      -(void)getUserData{
          if ([FBSDKAccessToken currentAccessToken]) {
              if ([FBSDKAccessToken currentAccessToken]) {
                  [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me?fields=id,name,token_for_business" parameters:nil]
                   startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                      if (!error) {
                          NSLog(@"--- fetched success, result: %@", result);
                      } else {
                          NSLog(@"--- fetched error: %@", error);
                      }
                  }];
              }
          } else {
              NSLog(@"--- no accessToken");
          }
      }
      
      @end
      

踩坑

编译报错: 找不到 swift 相关文件

报错: Undefined symbol: __swift_FORCE_LOAD_$_

原因是因为 sdk 使用了 swift, 而工程配置里没有配置 swift 头文件搜索的路径.

解决办法很简单: 创建一个 swift 文件即可, xcode 会提示创建桥接文件 Create Bridging Header

参考: https://github.com/facebook/react-native-fbsdk/issues/794

Facebook Swift SDK for Swift支持许多Facebook服务,包括Facebook分析、Facebook登录、分享到FacebookFacebook Graph API。该SDK以现有的Objective-C Facebook SDK为基础构建了一套封装器,旨在提供一种原生的Swift API和更简单的开发体验。Facebook Swift SDK支持两个最流行的iOS/macOS包管理系统CocoaPods和Carthage。使用CocoaPods添加该SDK的话,可以在Podfile中添加以下几行信息:pod 'FacebookCore' pod 'FacebookLogin' pod 'FacebookShare'如果使用Carthage,则可以在Cartfile中添加下面这行信息:github "facebook/Facebook-SDK-Swift"另外,你还可以将Facebook Swift SDK作为Xcode项目的子项目。不过使用这种方法时,你需要注意所有的依赖(FBSDKCoreKit.framework、FBSDKLoginKit.framework和FBSDKShareKit.framework,等等)及它们的升级。Facebook Swift SDK的GitHub库包含一个示例项目,说明如何将支持的服务集成进你的应用。下面是一个如何使用该SDK提供的ShareDialogViewController分享照片的例子:let photo = Photo(image: UIImage(named: "sky.jpg")!, userGenerated: true) let content = PhotoShareContent(photos: [photo]) let dialog = ShareDialog(content: content) dialog.presentingViewController = self dialog.mode = .Automatic do {     try dialog.show() } catch (let error) {     let alertController = UIAlertController(title: "Invalid share content", message: "Failed to present share dialog with error \(error)")     presentViewController(alertController, animated: true, completion: nil) }Facebook Swift SDK面向Swift 2.2.1和2.3,允许开发人员将应用提交到应用商店。介绍摘自:http://www.infoq.com/cn/news/2016/07/facebook-swift-sdk 标签:FaceBook
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蝶泳奈何桥.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值