ios - Facebook 快速登录

标签 ios swift facebook facebook-login

我正在尝试以 swift 实现 facebook 登录。我目前遇到错误

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

我目前的实现如下:

我的 Pod 文件:

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 中的建议。我找不到步骤,我做错了。非常感谢任何帮助。

最佳答案

导入 SDK:

  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

在info.plist中添加FB id

image-2

关于ios - Facebook 快速登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53680189/

相关文章:

android - 如何将 map 列表作为初始值传递给flutter_form_builder包中的FormBuilder FilterChip?

ios - 使用 Gloss 框架的可解码、可编码、光泽一致性问题

swift - 正向地理编码后如何返回坐标?

php - 目标 [League\OAuth2\Server\Repositories\ClientRepositoryInterface] 在构建 [League\OAuth2\Server\AuthorizationServer] 时不可实例化

Facebook Tab App 和 SSL 证书

ios - 如何将 ruby​​ 中的随机字符串传递给 iOS 应用程序?

ios - 使用 block 的返回值动态创建字符串

swift - 计算 Swift 字符串中的行数

ios - 使用 16 位 PCM 在 iOS 中生成音调,AudioEngine.connect() 抛出 AUSetFormat : error -10868

android - 该应用程序请求了无效的权限 - Facebook api