Facebook войти в Swift - PullRequest
       12

Facebook войти в Swift

0 голосов
/ 08 декабря 2018

Я пытаюсь реализовать вход в Facebook в Swift.В настоящее время я получаю сообщение об ошибке

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

Моя текущая реализация выглядит следующим образом:

Файл моего модуля:

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

Файл моего приложения:

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:.
}


}

и моя реализация ViewController:

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

Я выполнил шаги, упомянутые в руководстве facebook login ios , а также использовал предложения в this .Я не могу найти шаги, я сделал неправильно.Любая помощь очень ценится.

1 Ответ

0 голосов
/ 08 декабря 2018

Imprt SDKs:

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

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

}

В 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

            }
        })
    }
}

Добавить в информацию

Image-1

Добавить идентификатор FB в info.plist

image-2

...