简体   繁体   English

通过 swift 集成新的 facebook SDK

[英]Integration new facebook SDK by swift

Today i tried to integrate facebook SDK to my Swift app but in the quick start on facebook guide page looks a bit different than my old code.今天我尝试将 facebook SDK 集成到我的 Swift 应用程序中,但在 facebook 指南页面上的快速入门看起来与我的旧代码有点不同。 How can i convert OBJ-C code below to swift?如何将下面的 OBJ-C 代码转换为 swift?

- (void)applicationDidBecomeActive:(UIApplication *)application {
  [FBSDKAppEvents activateApp];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                    didFinishLaunchingWithOptions:launchOptions];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                         openURL:url
                                               sourceApplication:sourceApplication
                                                      annotation:annotation];
}

Thanks!谢谢!

It's pretty much the same, except instead of using brackets, you use dots.它几乎相同,除了使用点而不是使用括号。

func applicationDidBecomeActive(application: UIApplication!) {
    FBSDKAppEvents.activateApp()
}

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}

Swift 3 with Swift FacebookSDK Swift 3 与 Swift FacebookSDK

Podfile播客文件

pod 'FacebookCore'
pod 'FacebookLogin'

info.plist信息.plist

no changes from old sdk旧的sdk没有变化

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fb$(YOUR_FB_APP_ID)</string>
        </array>
    </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>
<key>FacebookAppID</key>
<string>$(YOUR_FB_APP_ID)</string>
<key>FacebookDisplayName</key>
<string>$(YOUR_APP_NAME)</string>

AppDelegate.swift AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    ...
}

func applicationDidBecomeActive(_ application: UIApplication) {
    AppEventsLogger.activate(application)
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let appId = SDKSettings.appId
    if url.scheme != nil && url.scheme!.hasPrefix("fb\(appId)") && url.host ==  "authorize" { // facebook
        return SDKApplicationDelegate.shared.application(app, open: url, options: options)
    }
    return false
}

...

LoginManager (custom login, see docs for default/button implementation) LoginManager(自定义登录,请参阅文档以了解默认/按钮实现)

contains custom code but you get the point包含自定义代码,但您明白了

let facebookManager = LoginManager(loginBehavior: .systemAccount, defaultAudience: .everyone)
func loginWithFacebook() {
    self.facebookManager.logIn(HAAccountManager.shared.facebookPermissions, viewController: self) { (result) in
        switch result {
        case .failed(let error):
            self.showAlert(forError: error as NSError)
        case .cancelled:
            print("FB login cancelled")
        case .success(let grantedPermissions, let deniedPermissions, let accessToken):
            if grantedPermissions.contains(Permission(name: "email")) == true {
                ApiClient.shared.facebookSignIn(authToken: accessToken.authenticationToken, completion: { (err, user) in
                    if err == nil {
                        // success
                    }
                    else {
                        self.showAlert(forError: err!)
                    }
                })
            }
            else {
                self.showAlert(forError: HAError(title: String(format: String.somethingError, String.signIn), message: grantedPermissions.contains(Permission(name: "email")) == true ? String.noAccountFound : String.missingEmailForSignUp))
            }
        }
    }
}

Analytics分析

// custom ex
AppEventsLogger.log(AppEvent(name: "open_app", parameters: ["logged_in": NSNumber(value: HAAccountManager.shared.isUserLoggedIn())], valueToSum: nil))

// purchase ex
AppEventsLogger.log(
    AppEvent.purchased(
        amount: Double(revenue),
        currency: currency,
        extraParameters: [
            AppEventParameterName.contentId : orderId,
            AppEventParameterName.itemCount : order.orderItems.count.nsNumber()
        ])
)

This has been depricated in iOS 10 .这已在iOS 10弃用。

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {

For Swift 3.0 , you can use:对于Swift 3.0 ,您可以使用:

Swift 3.0斯威夫特 3.0

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let isHandled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[.sourceApplication] as! String!, annotation: options[.annotation])
    return isHandled
}

I know this is a pretty old question here but it seams that it will never be outdated as Facebook hasn't updated their QuickStart guide for a long time.我知道这是一个非常古老的问题,但它似乎永远不会过时,因为 Facebook 很长时间没有更新他们的快速入门指南。

So here is the solution for Swift 4.x.所以这里是 Swift 4.x 的解决方案。

In didFinishLaunching:在 didFinishLaunching 中:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FBSDKApplicationDelegate.sharedInstance()?.application(application, didFinishLaunchingWithOptions: launchOptions)

    return true
}

In open Url:在打开的网址中:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

    let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[.sourceApplication] as? String, annotation: options[.annotation])
    return handled
}

Swift 5 with FBSDKCoreKit (5.3.0)带有 FBSDKCoreKit (5.3.0) 的 Swift 5

Import FBSDKCoreKit in appdelegate在 appdelegate 中导入FBSDKCoreKit

In didFinishLaunching:在 didFinishLaunching 中:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FBSDKCoreKit.ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    return true
}

In open Url:在打开的网址中:

  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    let handled = FBSDKCoreKit.ApplicationDelegate.shared.application(app, open: url, options: options)
    return handled
}

In iOS 9 i use:在 iOS 9 中,我使用:

func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
{   
    FBSDKApplicationDelegate.sharedInstance().application(app, openURL: url, sourceApplication: options["UIApplicationOpenURLOptionsSourceApplicationKey"] as! String, annotation: options["UIApplicationOpenURLOptionsAnnotationKey"])
    return true
}

On iOS 9 you should be using:在 iOS 9 上你应该使用:

func application(application: UIApplication,openURL url: NSURL, options: [String: AnyObject]) -> Bool {
   return ApplicationDelegate.shared.application(application, openURL: url, sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String, annotation: annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}

I found the potential for the Application delegate to break in iOS 9 with the annotation: options[UIApplicationOpenURLOptionsAnnotationKey] as it will not accept nil values.我发现应用程序委托有可能在 iOS 9 中使用注释中断: options[UIApplicationOpenURLOptionsAnnotationKey]因为它不接受 nil 值。 You can set this to a blank string and the application should run fine with facebook after this.您可以将其设置为空白字符串,此后应用程序应该可以与 facebook 一起正常运行。

Swift 2.2 docs: Swift 2.2 文档:

You specify optional chaining by placing a question mark (?) after the optional value on which you wish to call a property, method or subscript if the optional is non-nil.如果可选项非零,您可以通过在您希望调用属性、方法或下标的可选项值后面放置一个问号 (?) 来指定可选项链。 This is very similar to placing an exclamation mark (!) after an optional value to force the unwrapping of its value.这与在可选值后放置感叹号 (!) 以强制展开其值非常相似。 The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.主要区别在于,当 optional 为 nil 时,可选链会优雅地失败,而当 optional 为 nil 时,强制解包会触发运行时错误。

In swift 3.0.1在 swift 3.0.1

return GIDSignIn.sharedInstance().handle(url, sourceApplication:    
options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation:     
options[UIApplicationOpenURLOptionsKey.annotation])

Since I want to support iOS 8, I have modified the function application(_:open:options:) in Whitney Foster's answer to由于我想支持iOS 8,我在Whitney Foster的回答中修改了函数application(_:open:options:)

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let appId = SDKSettings.appId
    if url.scheme != nil && url.scheme!.hasPrefix("fb\(appId)") && url.host ==  "authorize" { // facebook
        if #available(iOS 9.0, *) {
            return SDKApplicationDelegate.shared.application(app, open: url, options: options)
        }
    }
    return false
}

and implemented additional fallback function并实现了额外的回退功能

// Fallback on earlier versions
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return SDKApplicationDelegate.shared.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
if let fbSDKAppId = FBSDKSettings.appID(),
            url.scheme!.hasPrefix("fb\(fbSDKAppId)"),
            url.host == "authorize" { // facebook
            return FBSDKApplicationDelegate.sharedInstance().application(application,
                                                                         open: url,
                                                                         sourceApplication: sourceApplication,
                                                                         annotation: annotation)
}

For swift 5 with latest FBSDK (FBSDKCoreKit 5.2.1)对于带有最新 FBSDK (FBSDKCoreKit 5.2.1) 的 swift 5

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let handled = ApplicationDelegate.shared.application(app, open: url, options: options)

        return handled
    }

Looks like Facebook gave up on Apple and has stopped updating their docs for years.看起来 Facebook 放弃了 Apple,并且多年来一直停止更新他们的文档。

As of 2021, this is what works for me with FBSDKCoreKit 9.0.0 and Swift 5.截至 2021 年,这对我来说适用于 FBSDKCoreKit 9.0.0 和 Swift 5。

  1. The pod to use is FBSDKCoreKit/Core (without Core, it will just be basics, and will be missing classes such as AppDelegate).要使用的 pod 是FBSDKCoreKit/Core (如果没有 Core,它将只是基础,并且将缺少 AppDelegate 等类)。

  2. Import FBSDKCoreKit and setup with ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) .导入FBSDKCoreKit并使用ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM