Integration new facebook SDK by swift
28,384
Solution 1
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)
}
Solution 2
Swift 3 with Swift FacebookSDK
Podfile
pod 'FacebookCore'
pod 'FacebookLogin'
info.plist
no changes from old 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
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)
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()
])
)
Solution 3
This has been depricated in iOS 10
.
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
For Swift 3.0
, you can use:
Swift 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
}
Solution 4
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.
So here is the solution for Swift 4.x.
In 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
}
Solution 5
Swift 5 with FBSDKCoreKit (5.3.0)
Import FBSDKCoreKit in appdelegate
In 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
}
Author by
Varis Darasirikul
Updated on July 23, 2022Comments
-
Varis Darasirikul almost 2 years
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?
- (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!
-
Dustin Nielson about 9 yearsThis was helpful for me but It would be great if someone could whip up a quick tutorial for logging into facebook using the new sdk. I've gotten so far as to get the button to render.
-
HungryArthur about 9 yearsThere is a very clear tutorial and example here : brianjcoleman.com/…
-
snibbe over 8 yearsNote that openURL:sourceApplication:annotation is deprecated in iOS 9 (stackoverflow.com/questions/33737403/…). Instead use
return FBAppCall.handleOpenURL(url, sourceApplication: options["UIApplicationOpenURLOptionsSourceApplicationKey"] as! String
-
code_ada over 8 yearsreturn FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) line fails saying use of unresolved identifier sourceApplication and same for annotation.
-
DàChún over 7 yearsit works. but seems it is different from the official documentation: developers.facebook.com/quickstarts/873570042741264/… - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
-
Whitney Foster over 7 yearsyeah the check for the "fb" is to support other frameworks (braintree and branch for my app) @User9527
-
E-Madd almost 7 yearsThanks. Someone at Facebook should have to go through their own quick start docs every month to see if they're horribly outdated
-
RoyBS about 6 yearsThank you so much, you're a life saver
-
Pradeep Kashyap almost 5 yearsfor new sdk(5.0.0) did finish code : ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) and for open URL : let handled = ApplicationDelegate.shared.application(app, open: url, sourceApplication: options[.sourceApplication] as? String, annotation: options[.annotation])