2

I am trying to implement facebook login in swift. I am currently getting error

The operation couldn’t be completed. (com.facebook.sdk.core error 3.)

My current implementation are as follows:

My pod file:

target 'AlamofireTest' do
# Comment the next line if you're not using Swift and don't want to use 
dynamic frameworks
use_frameworks!

# Pods for AlamofireTest
pod 'Alamofire'
pod 'AlamofireImage'
pod 'FBSDKLoginKit'

target 'AlamofireTestTests' do
inherit! :search_paths
# Pods for testing
end

target 'AlamofireTestUITests' do
inherit! :search_paths
# Pods for testing
end

end

My Appdelegate file:

import UIKit
import FBSDKCoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FBSDKApplicationDelegate.sharedInstance()?.application(application, didFinishLaunchingWithOptions: launchOptions)
    return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    let handled = FBSDKApplicationDelegate.sharedInstance()?.application(app, open: url, options: options)
    return handled!
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

and my ViewController implementation:

@IBAction func loginWithFacebook(_ sender: Any) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
    fbLoginManager.logIn(withReadPermissions: ["public_profile","email"], from: self) { (result, error) -> Void in
        if error != nil {
            print(error!.localizedDescription)
            self.dismiss(animated: true, completion: nil)
        } else if result!.isCancelled {
            print("Cancelled")
            self.dismiss(animated: true, completion: nil)
        } else {
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, relationship_status"]).start(completionHandler: { (connection, result, error) -> Void in
                if (error == nil){
                    let fbDetails = result as! NSDictionary
                    print(fbDetails)
                }
            })
        }
    }
}

I have followed the steps mentioned in the guide facebook login ios, and also used the suggestions in this. I am unable to find the steps, I did wrong. Any help is much appreciated.

SarojMjn
  • 569
  • 1
  • 7
  • 23

2 Answers2

2

Imprt SDKs:

  1. FBSDKCoreKit.framework
  2. Bolts.framework
  3. FBSDKLoginKit.framework

In Appdelegate.swift

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool
{
    return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}

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

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

}

In ViewController.swift

@IBAction func ButtonClickFB(_ sender: Any){

    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logOut()

    fbLoginManager.logIn(withReadPermissions:["email","user_friends","user_birthday"], from: self, handler: { (result, error) -> Void in
        if ((error) != nil)
        {
            // Process error
            //  print(error)
        }
        else if (result?.isCancelled)!
        {
            // Handle cancellations
            // print(error)
        }
        else
        {
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.getFBUserData()
                // fbLoginManager.logOut()
            }
        }
    })

}

    func getFBUserData () {
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(normal), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){

                print((result! as AnyObject))
                //  print(((result! as AnyObject).value(forKey: "id") as? String)!)

                self.strEmail = ((result! as AnyObject).value(forKey: "email") as? String) ?? ""
                self.strID = ((result! as AnyObject).value(forKey: "id") as? String) ?? ""
                self.strName = ((result! as AnyObject).value(forKey: "name") as? String) ?? ""

                self.TextFBEmail.text = self.strEmail

            }
        })
    }
}

Add this in info

Image-1

Add FB id in info.plist

image-2

B K.
  • 534
  • 5
  • 18
0

Facebook Signin

Step0.

Create Project on Facebook Console and get Keys and URL Schme.

Step1.

Modify Info.plist,


<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb17996xxxxxxx</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>179962xxxxxx</string>
<key>FacebookDisplayName</key>
<string>Restman</string>

<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>

Step2.

Change AppDelegate,


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

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

    return true
}

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

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

    return handled
}

Step3.

On your View,



FacebookLoginHelper.shared.authenticate(view: self) { (isLoggedIn) in

    if isLoggedIn {
    
        FacebookLoginHelper.shared.getUserProfile(onCompletion: { (user) in

            print(user)
        })
    }
}

Step4. FacebookLoginHelper.swift

//
//  FacebookLoginHelper.swift
//  FacebookSigInDemo
//
//  Created by Brahma on 04/02/23.
//

import Foundation
import FBSDKCoreKit
import FBSDKLoginKit

struct FacebookUser {
    var name: String!
    var email: String!
    var userID: String!
    var imagePath: String?
}

class FacebookLoginHelper {
    
    private let manager = FBSDKLoginManager()
    private let facebookKeys = ["public_profile", "email"]
    private let graphDict = ["fields": "id, name, picture.type(large), email"]
    
    public static let shared = FacebookLoginHelper()
    
    private func prepareUser(dict:[String:Any]) -> FacebookUser  {
        
        var user = FacebookUser()
        user.name = dict["name"] as? String
        user.email = dict["email"] as? String
        user.userID = dict["id"] as? String
        
        return user
    }
    
    public func authenticate(view: UIViewController, onCompletion:@escaping (Bool)->()) {
        
        manager.logIn(withReadPermissions: facebookKeys, from: view) { (result, error) in
            if let status = result {
                if !status.isCancelled {
                    //onSuccess
                    onCompletion(true)
                }
                //onFail
                onCompletion(false)
            }
        }
    }
    
    public func getUserProfile(onCompletion:@escaping (FacebookUser)->()) {
        
        if FBSDKAccessToken.current() != nil {
            FBSDKGraphRequest(graphPath: "me", parameters: graphDict).start { (connection, result, error) in
                
                if let dict = result as? [String:Any] {
                    let user = self.prepareUser(dict: dict)
                    onCompletion(user)
                }
            }
        }
        else {
            //onError
        }
    }
    
    public func logout() {
        manager.logOut()
    }
    
}

Mannam Brahmam
  • 2,225
  • 2
  • 24
  • 36