ios - 了解iOS应用添加facebook登录的流程

标签 ios swift facebook-login facebook-ios-sdk

我拼命尝试将 facebook 登录与我的应用程序集成,但到目前为止没有成功。

  1. 我已经按照 firebase 和 facebook 网站上的说明安装了所需的 pod。

  2. 按照 firebase 提供的教程进行操作。

  3. 我想我已经向 AppDelegate 类和 LoginViewController 添加了所需的代码。 (我当然是添加两个类的代码):

  4. 我已经阅读了一些关于登录管理器和权限的内容,但 facebook 和 firebase 教程中都没有提到这些内容。

我好像搞不清楚这个过程的流程。当我按下 FBLoginButton(添加打印语句进行检查)时,委托(delegate)方法没有午餐。

我使用的是 Swift 5,对 objective-c 不是很好,所以快速的代码建议会很棒。

提前致谢!

//
//  LogInViewController.swift
//  Flash Chat
//
//  This is the view controller where users login
// Control–Command–Space bar to get emojes

import UIKit
import Firebase
import SVProgressHUD
import GoogleSignIn
import FirebaseUI
import FBSDKLoginKit
import FBSDKCoreKit

class LogInViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate, LoginButtonDelegate {


    //Textfields pre-linked with IBOutlets
    @IBOutlet var emailTextfield: UITextField!
    @IBOutlet var passwordTextfield: UITextField!
    @IBOutlet var fbLoginButton: FBLoginButton!
    @IBOutlet weak var upperView: UIView!
    @IBOutlet weak var warningLabel: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()
        addGesture()
        initGIDSignIn()
        initFBSignIn()
    }

    private func addGesture () {
        let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
        upperView.addGestureRecognizer(tapGesture)
    }

    private func roundCorners(button: UIButton) {
        button.layer.cornerRadius = 20
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.white.cgColor
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //MARK: Google Sign In

    private func initGIDSignIn () {
        GIDSignIn.sharedInstance().uiDelegate = self
        GIDSignIn.sharedInstance().delegate = self
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    }

    @IBAction func signInViaGooglePressed(_ sender: UIButton) {
        GIDSignIn.sharedInstance()?.signIn()
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
        if error != nil {
            print("Error")
            return
        }
        guard let authentication = user.authentication else { return }
        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                       accessToken: authentication.accessToken)
        Auth.auth().signIn(with: credential) { (authResult, error) in
            if error != nil {
                print("Error")
                return
            }
            self.performSegue(withIdentifier: "goToChat", sender: self)
        }

    }

    func sign(_ signIn: GIDSignIn!,present viewController: UIViewController!) {
        self.present(viewController, animated: true, completion: nil)
    }

    func sign(_ signIn: GIDSignIn!,dismiss viewController: UIViewController!) {
        self.dismiss(animated: true, completion: nil)
    }

    //MARK: Facebook Sign In

    private func initFBSignIn () {
        fbLoginButton = FBLoginButton()
        fbLoginButton.delegate = self
    }

    func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?, error: Error?) {
        print("Got to this place")
        if error != nil {
            print("Error")
            return
        }

        let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
        Auth.auth().signIn(with: credential) { (authResult, error) in
            if error != nil {
                print("Error!")
                return
            }
            self.performSegue(withIdentifier: "goToChat", sender: self)
        }
    }

    func loginButtonDidLogOut(_ loginButton: FBLoginButton) {
        print("logged out")
    }

    // MARK: Regular Login

    @IBAction func logInPressed(_ sender: AnyObject) {
        SVProgressHUD.show()
        if checkDetailsValidity(){
            Auth.auth().signIn(withEmail: emailTextfield.text!, password: passwordTextfield.text!) { (user, error) in
                if error != nil {
                    self.warningLabel.text = "Incorrect email or password"
                    SVProgressHUD.dismiss()
                }
                else {
                    SVProgressHUD.dismiss()
                    print("Successfuly logged in!")
                    self.performSegue(withIdentifier: "goToChat", sender: self)
                }
            }
        }
        else {
            SVProgressHUD.dismiss()
        }
    }

    private func checkDetailsValidity() -> Bool {
        if emailTextfield.text!.isEmpty {
            warningLabel.text = "Email is mandatory field"
            return false
        }
        else if !emailTextfield.text!.contains("@") || !emailTextfield.text!.contains("."){
            warningLabel.text = "Email is illegal"
            return false
        }
        return true
    }
}  
import UIKit
import Firebase
import GoogleSignIn
import FBSDKCoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        return true
    }

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



    @available(iOS 9.0, *)
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        if (GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                             annotation: options[UIApplication.OpenURLOptionsKey.annotation]))
        {
            return true;

        }else if(url.absoluteString.contains("www.mydomain.com")){
            print("incoming url \(url.absoluteString)")

            return true
        }
        else if ApplicationDelegate.shared.application(app, open: url, sourceApplication: options[.sourceApplication] as? String, annotation: options[.annotation]) {
                return true

        }

        return false
    }

//    // [START openurl]
//    @available(iOS 8.0, *)
//    func application(_ application: UIApplication,
//                     open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
//
//
//        if (GIDSignIn.sharedInstance().handle(url,
//                                              sourceApplication: sourceApplication,
//                                              annotation: annotation))
//        {
//            return true;
//        }else if(url.absoluteString.contains("www.mydomain.com")){
//
//            print("incoming url \(url.absoluteString)")
//            return true
//        }
//
//        return false;
//
//    }






}

最佳答案

application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) 中,确保添加以下代码:

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

看来你只是在呼唤...

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

...混淆了两者。试试这个,如果有帮助请告诉我。

关于ios - 了解iOS应用添加facebook登录的流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57437188/

相关文章:

ios - 使用 swift 将 iOS 应用程序连接到 sockJs 服务器

iphone - 返回/传递引用作为其协议(protocol)

ios - 将附件发送到 QuickBlox IOS sdk

ios - NSDecimalNumber decimalNumberWithString : ignores current locale

swift - 编译器不理解 NSTimeInterval 上的 Nil 合并运算符

符合具有默认实现的协议(protocol)的类型的 Swift 最小实现

iOS 10 的 Facebook 登录问题

java - 如何让 Facebook 登录带我去 Activity ?

ios - 为什么我的 ImageView 不起作用以及为什么该 View 显示为空白屏幕?

java - Uncaught Error : No polyfill registered for object Facebook JDK