Как я могу войти в Facebook с помощью кнопки SwiftUI - PullRequest
1 голос
/ 04 мая 2020

Я не могу войти в Facebook, gmail уже сделан, но Facebook не работает для меня, удалите код Facebook, чтобы дать мне идею, потому что видео-уроки, которые я видел только покажите, что Facebook приносит по умолчанию, и я хочу сделать это с помощью кнопки с дизайном, который я показываю ниже. Если кто-то может помочь мне решить эту проблему, я буду очень признателен.

Дизайн входа

introducir la descripción de la imagen aquí

Здесь я покажу вам код AppDelegate.swift

    import UIKit
    import Firebase
    import GoogleSignIn

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {



        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch.
            FirebaseApp.configure()
            GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
            GIDSignIn.sharedInstance().delegate = self
            return true
        }

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

        func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
          // ...
          if let error = error {
            // ...
            print(error.localizedDescription)
            return
          }

          guard let authentication = user.authentication else { return }
          let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                            accessToken: authentication.accessToken)
            Auth.auth().signIn(with: credential){(res, err) in
                if err != nil {
                    print((err?.localizedDescription)!)
                    return
                }
                print("user=" + (res!.user.email)!)
            }
        }
        func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
            // Perform any operations when the user disconnects from app here.
            // ...
        }

        // MARK: UISceneSession Lifecycle

        func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
            // Called when a new scene session is being created.
            // Use this method to select a configuration to create the new scene with.
            return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
        }

        func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
            // Called when the user discards a scene session.
            // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
            // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
        }


    }

Здесь я покажу вам код ContentView.swift

import SwiftUI
import GoogleSignIn
import FBSDKLoginKit

struct ContentView: View {
    var body: some View {
        ZStack{
            LinearGradient(gradient: .init(colors: [Color("Color"), Color("Color1"), Color("Color2")]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
            if UIScreen.main.bounds.height > 800 {

                Home()
            }else {
                ScrollView(.vertical, showsIndicators: false) {
                    Home()
                }
            }
        }.environment(\.colorScheme, .light)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct Home :  View{

    var body : some View{
        VStack {
            Image("logo")
                .resizable()
                .frame(width: 200, height: 180)

            HStack(spacing: 15){
                Color.white.opacity(0.7)
                    .frame(width: 35, height: 1)

                Text("Iniciar Sesión")
                    .fontWeight(.bold)
                    .foregroundColor(.white)

                Color.white.opacity(0.7)
                    .frame(width: 35, height: 1)

            }
            .padding(.top, 10)

            HStack{
                Button(action: {

               }){
                    Image("fb")
                        .renderingMode(.original)
                        .padding()
                }.background(Color.white)
                    .clipShape(Circle())


                Button(action: {
                    GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.last?.rootViewController
                    GIDSignIn.sharedInstance()?.signIn()

                }){
                    Image("google")
                        .renderingMode(.original)
                        .padding()
                }.background(Color.white)
                    .clipShape(Circle())
                    .padding(.leading, 25)
            }
            .padding(.top, 10)

        }.padding()
    }
}

Код показывает эти две ошибки !!!

enter image description here enter image description here

1 Ответ

1 голос
/ 04 мая 2020

Попробуйте это.

import FirebaseAuth
import FBSDKLoginKit

struct LoginView: View {
    private let premission = ["public_profile", "email"] //added
    var body: some View {
        VStack{
            ...
            Button(action: {
                self.FacebookLogin()
            }, label: {
                Text("LOGIN WITH FACBOOK")
            })
            ...
        }
    //}  removed

    func FacebookLogin() {
        let fbLoginManager = LoginManager()
        fbLoginManager.logIn(permissions: premission, from: UIHostingController(rootView: LoginView())) { (result, error) in
            if let error = error {
                print("Failed to login: \(error.localizedDescription)")
                let alertController = UIAlertController(title: "Login Error", message: error.localizedDescription, preferredStyle: .alert)
                let okayAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                alertController.addAction(okayAction)
                return
            }

            guard let _ = AccessToken.current else {
                print("Failed to get access token")
                return
            }

            if result?.isCancelled == true {
                print("User canceled")
                return
            }

            let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)


            Auth.auth().signIn(with: credential, completion: { (user, error) in
                if let error = error {
                    print("Login error: \(error.localizedDescription)")
                    let alertController = UIAlertController(title: "Login Error", message: error.localizedDescription, preferredStyle: .alert)
                    let okayAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(okayAction)
                    print("asd")
                    return
                }

                return

            })
        }
    }

}
} //added
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...