ios 通过 swift 集成新的 facebook SDK

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29277494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:21:22  来源:igfitidea点击:

Integration new facebook SDK by swift

iosobjective-ciphonefacebookswift

提问by Varis Darasirikul

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. How can i convert OBJ-C code below to swift?

今天我尝试将 facebook SDK 集成到我的 Swift 应用程序中,但在 facebook 指南页面上的快速入门看起来与我的旧代码有点不同。如何将下面的 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!

谢谢!

回答by Sean

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)
}

回答by Whitney Foster

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()
        ])
)

回答by Tal Zion

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
}

回答by Tomte

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
}

回答by Pavel Z.

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
}

回答by Ranjani

Swift 5 with FBSDKCoreKit (5.3.0)

带有 FBSDKCoreKit (5.3.0) 的 Swift 5

Import FBSDKCoreKitin 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
}

回答by H2wk

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. You can set this to a blank string and the application should run fine with facebook after this.

我发现应用程序委托可能会在 iOS 9 中使用注释中断:options[UIApplicationOpenURLOptionsAnnotationKey]因为它不会接受 nil 值。您可以将其设置为空白字符串,此后应用程序应该可以与 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 时,强制解包会触发运行时错误。

回答by Abdelhak

In swift 3.0.1

在 swift 3.0.1

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

回答by Protocole

Since I want to support iOS 8, I have modified the function application(_:open:options:)in Whitney Foster's answerto

因为我想支持iOS 8的,我已经修改了功能,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)
}

回答by Svitlana

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)
}