FirebaseAuth со Swift не работает (отображается пустое приветствие V C) - PullRequest
0 голосов
/ 26 мая 2020

У меня странная проблема. Я не могу показать какие-либо параметры аутентификации и получаю только пустой ViewController, когда пытаюсь использовать FirebaseAuth / FirebaseUI

Кто-нибудь знает, что я мог сделать неправильно? Кстати. Email Auth включен. :)

Login ViewController

import UIKit
import FirebaseAuth
import FirebaseUI


typealias FIRUser = FirebaseAuth.User

class LoginViewController: UIViewController, UITextFieldDelegate {


// MARK: Properties

@IBOutlet weak var logInandSignUp: UIButton!


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


    override func viewWillAppear(_ animated: Bool) {
       }


// MARK: Actions

    @IBAction func loginButtonTapped(_ sender: UIButton) {
        print("Login Button tapped")





             // 1 access the FUIAuth default auth UI singleton
             guard let authUI = FUIAuth.defaultAuthUI()
                 else { return }

             // 2 set FUIAuth's singleton delegate
             authUI.delegate = self

             // 3 present the auth view controller
             let authViewController = authUI.authViewController()
             present(authViewController, animated: true, completion: nil)


    }

}



extension LoginViewController: FUIAuthDelegate {
    func authUI(_ authUI: FUIAuth, didSignInWith authDataResult: AuthDataResult?, error: Error?) {

        let user = User.current

        if let error = error {

            assertionFailure("Error signing in: \(error.localizedDescription)")
            return
        }

        UserService.show(forUID: user.uid) { (user) in
                if let user = user {
                    // handle existing user
                    User.setCurrent(user)

                    let initialViewController = UIStoryboard.initialViewController(for: .main)
                    self.view.window?.rootViewController = initialViewController
                    self.view.window?.makeKeyAndVisible()

                } else {
                    // handle new user
                    self.performSegue(withIdentifier: Constants.Segue.toCreateUsername, sender: self)
                }
            }
        }
    }

UserService.swift:

import Foundation
import FirebaseAuth.FIRUser
import FirebaseDatabase
import FirebaseUI
import FirebaseAuth

struct UserService {



    static func create(_ firUser: FIRUser, username: String, completion: @escaping (User?) -> Void) {

       let userAttrs = ["username": username]

        let ref = Database.database().reference().child("Leader").child(firUser.uid)
        ref.setValue(userAttrs) { (error, ref) in
            if let error = error {
                assertionFailure(error.localizedDescription)
                return completion(nil)
            }

            ref.observeSingleEvent(of: .value, with: { (snapshot) in
                let user = User(snapshot: snapshot)
                completion(user)
            })
        }
    }
    static func show(forUID uid: String, completion: @escaping (User?) -> Void) {
           let ref = Database.database().reference().child("users").child(uid)
           ref.observeSingleEvent(of: .value, with: { (snapshot) in
               guard let user = User(snapshot: snapshot) else {
                   return completion(nil)
               }

               completion(user)
           })
       }

}

User.swift

import Foundation
import FirebaseDatabase.FIRDataSnapshot

class User {

    // MARK: - Properties

    let uid: String
    let username: String

    // MARK: - Init

    init(uid: String, username: String) {
        self.uid = uid
        self.username = username
    }
    init?(snapshot: DataSnapshot) {
    guard let dict = snapshot.value as? [String : Any],
        let username = dict["username"] as? String
        else { return nil }

    self.uid = snapshot.key
    self.username = username
    }

    // MARK: - Singleton

    // Now that we've created a User singleton, we need to make sure to set it. Once we receive the user from the database, we set the singleton with our custom setter method. After the singleton is set, it will remain in memory for the rest of the app's lifecycle. It will be accessible from any view controller with the following code: let user = User.current


    // 1 Create a private static variable to hold our current user.
    private static var _current: User?

    // 2 Create a computed variable that only has a getter that can access the private _current variable.
    static var current: User {
        // 3 Check that _current that is of type User? isn't nil. If _current is nil --> fatalError().

        guard let currentUser = _current else {
            fatalError("Error: current user doesn't exist")
        }

        // 4 If _current isn't nil, it will be returned to the user.
        return currentUser
    }

    // MARK: - Class Methods

    // 5 Create a custom setter method to set the current user.

    static func setCurrent(_ user: User) {
        _current = user
    }

}

Надеюсь, кто-нибудь сможет мне помочь. На самом деле не понимаю, в чем проблема.

...