Facebook Login Integration in your iOS App(Swift, UIkit)2023: Step By Step
Hi, I am writing this article after successfully implementing the Facebook login authentication in my iOS app, The point of writing this article is to help people who got stuck in some error after following the Facebook developer's documentation just like me. Some security policies have changed in Meta/Facebook, which they have not updated in their developer documentation, which I will share with you in this article.
So without any further delay, Let's start,
- So first, you have to sign in to your Facebook account, if you don't have any, make it, and then go and sign in to your Facebook developer Account, giving you the link:https://developers.facebook.com/, where just go to my apps and sign in with your Facebook account.
- Now after that click on the create app section and give the name of your app and register and configure your app by adding your Bundle Identifier which you get after creating the Xcode project.
- Follow the same process stated in the documentation: https://developers.facebook.com/docs/facebook-login/ios
Some common errors you can get are as follows :
Thread 1: “app id not found. add a string value with your app id for the key
1>In this line of the code given below,
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fbyourappid</string>
</array>
</dict>
Don't forget to add fb before giving your app id, for example, fb12347897897.
To integrate the Facebook SDK in an iOS app, you would typically need to import the appropriate Facebook SDK framework and follow the configuration steps provided by Facebook.
So in place of
import FacebookLogin
import FacebookCore
// it is deprecated and does not work now
replace it with
import FBSDKCoreKit
import FBSDKLoginKit
// this will work
Otherwise, you will get this error given below,
Cannot find Application delegate in scope
Add this code in the sceneDelegate :
// SceneDelegate.swift
import FBSDKCoreKit
import FBSDKLoginKit
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else {
return
}
ApplicationDelegate.shared.application(
UIApplication.shared,
open: url,
sourceApplication: nil,
annotation: [UIApplication.OpenURLOptionsKey.annotation]
)
}
Add this code in the didFinishLaunchingWithOptions of the AppDelegate file :
// AppDelegate.swift
import UIKit
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
//// MARK: UISceneSession Lifecycle
// Rest remains same
Lastly,
Carefully make changes to the info.plist file, as you have to replace the dummy app id and client token with your unique app id and client token. And only make these changes inside the <string>, which is inside the <key>not on the key.
And you will get the app id from settings -> basic and the client token from settings -> advanced in the Facebook developer account.
And now coming to the final view controller part,
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController {
@IBOutlet weak var fbLoginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func fbloginTap(_ sender: Any) {
facebookLogin()
}
// Facebook login function
func facebookLogin() {
let loginManager = LoginManager()
loginManager.logIn(permissions: ["public_profile"], from: self) { (result, error) in
if let error = error {
// Handle login error here
print("Error: \(error.localizedDescription)")
} else if let result = result, !result.isCancelled {
// Login successful, you can access the user's Facebook data here
self.fetchFacebookUserData()
} else {
// Login was canceled by the user
print("Login was cancelled.")
}
}
}
// MARK: - Fetch Facebook User Data
func fetchFacebookUserData() {
if AccessToken.current != nil {
// You can make a Graph API request here to fetch user data
GraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"]).start { (connection, result, error) in
if let error = error {
// Handle API request error here
print("Error: \(error.localizedDescription)")
} else if let userData = result as? [String: Any] {
// Access the user data here
let userID = userData["id"] as? String
let name = userData["name"] as? String
// Handle the user data as needed
print("User ID: \(userID ?? "")")
print("Name: \(name ?? "")")
}
}
} else {
print("No active Facebook access token.")
}
}
}
That's it. I hope you have successfully implemented the Facebook login authentication in your app. If you face any problem related to it, you can let me know in the comments.
Thank you :)