11

I installed Facebook's Swift SDK via Cocoapods:

pod 'FacebookCore', :git => "https://github.com/facebook/facebook-sdk-swift"
pod 'FacebookLogin', :git => "https://github.com/facebook/facebook-sdk-swift"

I have followed the login instructions from Facebook's Swift SDK (https://developers.facebook.com/docs/swift/login) but cannot get it working.

Inside my view controller I have the following:

@objc fileprivate func facebookSignIn() {
    let loginManager = LoginManager()
    print("LOGIN MANAGER: \(loginManager)")
    loginManager.logIn([ .publicProfile, .email ], viewController: self) { loginResult in
        print("LOGIN RESULT! \(loginResult)")
        switch loginResult {
        case .failed(let error):
            print("FACEBOOK LOGIN FAILED: \(error)")
        case .cancelled:
            print("User cancelled login.")
        case .success(let grantedPermissions, let declinedPermissions, let accessToken):
            print("Logged in!")
            print("GRANTED PERMISSIONS: \(grantedPermissions)")
            print("DECLINED PERMISSIONS: \(declinedPermissions)")
            print("ACCESS TOKEN \(accessToken)")
        }
    }
}

"Login manager: etc." prints when I click the button and the web view opens. I can sign in via Facebook and then the web view goes blank and nothing happens. The app shows in my Facebook apps, so some authorisation has taken place, but if I click the "Done" button in the web view, the result to the callback is .cancelled and "User cancelled login." is printed.

I have added Keychain Sharing to my entitlements, and I've updated my info.plist:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string> [ FB STRING ] </string>
        </array>
    </dict>
</array>
<key>FacebookAppID</key>
<string>[ APP ID ]</string>
<key>FacebookDisplayName</key>
<string>[ APP NAME ]</string>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>

I've even changed my NSAppTransportSecurity settings.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

I know this is a duplicate of iOS 9 Facebook login simulator -canOpenURL: failed for URL: "fbauth2:///" - error: "(null)" and How to use Facebook iOS SDK on iOS 10 but none of the solutions there seem to work for me, unless I've missed something? Any suggestions are appreciated.

Several errors are printed also:

[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction


[error] error: (6922) I/O error for database at /var/mobile/Containers/Data/Application/F3D8E126-B0CC-4C06-81A5-D7A7F849B3BD/Documents/OfflineModel2.sqlite.  SQLite error code:6922, 'disk I/O error'

And when I don't have the FB app installed on my device, I get:

-canOpenURL: failed for URL: "fbauth2:/" - error: "The operation couldn’t be completed. (OSStatus error -10814.)"

9 Answers 9

22

Swift 3 and Swift 4

add this to your AppDelegate.swift

import FBSDKCoreKit
import FBSDKLoginKit

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

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
   return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}
4
  • @erdemgc You should not miss to import FBSDKCoreKit
    – LKM
    Dec 3, 2016 at 15:38
  • Yes, I changed the method of callback in App delegate (Swift 4) and it worked.
    – Anil Gupta
    Apr 4, 2018 at 14:05
  • Hi @Pan Mluvčí, I tried your solution but I still cannot get the fb profile photo to appear. The debug says: -canOpenURL: failed for URL: "fbauth2:/" - error: "The operation couldn’t be completed. Jul 31, 2018 at 23:41
  • @ConsBulaquena dude..... u should really double check facebook guide on how to integrate FB into your project. My personal guess is: you missing something in your .plist file.... like facebook id or something. Aug 1, 2018 at 6:56
21

You have to substitute didfinishlaunching and openurl AppDelegate methods with below:

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

public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool 
{
    return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}
2
  • I had to change SDKApplicationDelegate to FBSDKApplicationDelegate Oct 28, 2016 at 16:02
  • 3
    @ifedapoolarewaju In that case you should change your import to FacebookCore and FacebookLogin from the modules prefixed with FBSDK. Those are the old ones as far as I understand, but the Swift modules depend on them, which is they get pulled down with Pods.
    – nickdnk
    Jan 16, 2017 at 20:44
9

The FBSDK Libraries are deprecated. The newer libraries can be found in Facebook's Github repository.

For this particular error, implement the following application methods.

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

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

}
5

Swift 3.0

on your AppDelete.swift:

import FBSDKCoreKit
import FBSDKLoginKit

inside your:

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

add:

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

then create a new func as follows:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}
2

Using Cocoapods in Swift 3.0

Install cocoapods

pod 'FacebookCore'
pod 'FacebookLogin'

in AppDelegate.swift

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

and writedown Callback method

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

in your viewController

import FacebookCore
import FacebookLogin
import FBSDKLoginKit

after that in your fblogin button write down this code

@IBAction func faceBookLoginBtnAction(_ sender: Any) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if fbloginresult.grantedPermissions != nil {
                if(fbloginresult.grantedPermissions.contains("email")) {
                    if((FBSDKAccessToken.current()) != nil){
                        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
                            if (error == nil){
                                self.dict = result as! [String : AnyObject]
                                print(result!)
                                print(self.dict)
                            }
                        })
                    }   
                }
            }
        }
    }
}

and one more important thing add your facebookid into your project In the Project > Target > Info > URL Types section, set the proper Facebook ID and to the URL Schemes.

1

First thing you need to create an application to use Facebook login in your application. You can create an app on facebook from here

You need to set URL types, FacebookAppID, FacebookDisplayName and LSApplicationQueriesSchemes into your info.plist.

  1. Manually add the Facebook login framework or you can use cocoa pods as follows...

     pod 'FacebookCore' //latest one
     pod 'FacebookLogin' // for fb login
     pod 'FacebookShare' //for sharing on fb
    

    and then pod install command to install pods for your application.

  2. import FacebookCore in your application delegate to use Facebook login

  3. Set up following things in AppDelegate.swift file:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
      return SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    
       if url.absoluteString.contains(<Your FBAppID>) {
          return SDKApplicationDelegate.shared.application(app, open: url, options: options)
        } else {
           debugPrint("Error in openURL from AppDelegate Facebook Sign in")
        }
    
        return true
    
     }
    

And now you are successfully configured Facebook login into your app.

In your view controller, you need to do the following:

import FacebookLoginKit

In your IBAction Method do the following:

@IBAction func btnFacebookSignInTapped(_ sender: UIButton) {

    let fbManager = FBSDKLoginManager()
    fbManager.logIn(withReadPermissions: ["public_profile", "email"], from: self) { (result, error) in

        if let loginResult = result, error == nil {

            if let permissions = loginResult.grantedPermissions {

                if permissions.contains("email") || permissions.contains("public_profile")  {

                    if FBSDKAccessToken.current() != nil {

                        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, graphResult, error) in

                            if error == nil {
                                debugPrint("Result: \(graphResult!)")
                                if let data = graphResult as? [String: Any] {
                                    print("User details from FB: \(data)")
                                }
                            }
                        })

                    } else {
                        print("Invalid FB access token");
                    }
                }

            } else {
                print("Fail to login using facebook.")
            }

        } else {
            print("Error in facebook login")
        }
    }
}

By doing so you will be able to login to Facebook.

0

updated for swift 3 :

// In your AppDelegate() :

// Step - 1:

import FacebookCore

//Step - 2: In didFinishLaunchingWithOptions()

 // FB Settings
 SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

// Instance Method():

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

    print("URL AbsoluteString = \(url.absoluteString)")

   if url.absoluteString.contains("fb1279300242197274") {
        return SDKApplicationDelegate.shared.application(app,
                                                         open: url,
                                                         options: options)

    }
    else {
        //return PDKClient.sharedInstance().handleCallbackURL(url)
        print("Error while open URL from app delegate facebook sign in")
    }

    return true
}
0

Answers here recommend using following implementation of application(_,didFinishLaunchingWithOptions:):

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

However, note that official documentation doesn't use the return value of

SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

as the return value of application(_,didFinishLaunchingWithOptions:).

Now while this might seem like unimportant, I've had big problems while integrating facebook SDK with branch deep linking, because exactly this line cause me problems. Therefore, if you want to prevent some unnecessary problems later, use the following solution:

public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool
{
    SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    // always return true
    return true
}

public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
{
    return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}
0

Other way to do it. Hope this video be helpfull for you https://youtu.be/bOS4jqRc8Io

Contents in this Video: Facebook SDK integration tutorial with Swift lastest 2018 Xcode new project setup Swift iOS app login with Facebook Tutorial Facebook login feature in iOS app Add Facebook to Swift iOS app Facebook login in iOS app

Steps: 1. Create new simple Swift Xcode project 2- Login to facebook develop page to create the same name APP 3- Add login with Facebook button, login and logout methods 4- Modify the configure plist, create bridging header for C, configure AppDelegate, 5- Run the application and test with simulator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.